def savetxt(fname, X, fmt='<STR_LIT>', delimiter='<STR_LIT:U+0020>', newline='<STR_LIT:\n>', header='<STR_LIT>',<EOL>footer='<STR_LIT>', comments='<STR_LIT>'):

<EOL>if isinstance(fmt, bytes):<EOL><INDENT>fmt = asstr(fmt)<EOL><DEDENT>delimiter = asstr(delimiter)<EOL>own_fh = False<EOL>if _is_string_like(fname):<EOL><INDENT>own_fh = True<EOL>if fname.endswith('<STR_LIT>'):<EOL><INDENT>import gzip<EOL>fh = gzip.open(fname, '<STR_LIT:wb>')<EOL><DEDENT>else:<EOL><INDENT>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>fh = open(fname, '<STR_LIT:wb>')<EOL><DEDENT>else:<EOL><INDENT>fh = open(fname, '<STR_LIT:w>')<EOL><DEDENT><DEDENT><DEDENT>elif hasattr(fname, '<STR_LIT>'):<EOL><INDENT>fh = fname<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>X = np.asarray(X)<EOL>if X.ndim == <NUM_LIT:1>:<EOL><INDENT>if X.dtype.names is None:<EOL><INDENT>X = np.atleast_2d(X).T<EOL>ncol = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>ncol = len(X.dtype.descr)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ncol = X.shape[<NUM_LIT:1>]<EOL><DEDENT>iscomplex_X = np.iscomplexobj(X)<EOL>if type(fmt) in (list, tuple):<EOL><INDENT>if len(fmt) != ncol:<EOL><INDENT>raise AttributeError('<STR_LIT>' % str(fmt))<EOL><DEDENT>format = asstr(delimiter).join(map(asstr, fmt))<EOL><DEDENT>elif isinstance(fmt, str):<EOL><INDENT>n_fmt_chars = fmt.count('<STR_LIT:%>')<EOL>error = ValueError('<STR_LIT>' % fmt)<EOL>if n_fmt_chars == <NUM_LIT:1>:<EOL><INDENT>if iscomplex_X:<EOL><INDENT>fmt = ['<STR_LIT>' % (fmt, fmt), ] * ncol<EOL><DEDENT>else:<EOL><INDENT>fmt = [fmt, ] * ncol<EOL><DEDENT>format = delimiter.join(fmt)<EOL><DEDENT>elif iscomplex_X and n_fmt_chars != (<NUM_LIT:2> * ncol):<EOL><INDENT>raise error<EOL><DEDENT>elif ((not iscomplex_X) and n_fmt_chars != ncol):<EOL><INDENT>raise error<EOL><DEDENT>else:<EOL><INDENT>format = fmt<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % (fmt,))<EOL><DEDENT>if len(header) > <NUM_LIT:0>:<EOL><INDENT>header = header.replace('<STR_LIT:\n>', '<STR_LIT:\n>' + comments)<EOL>fh.write(asbytes(comments + header + newline))<EOL><DEDENT>if iscomplex_X:<EOL><INDENT>for row in X:<EOL><INDENT>row2 = []<EOL>for number in row:<EOL><INDENT>row2.append(number.real)<EOL>row2.append(number.imag)<EOL><DEDENT>fh.write(asbytes(format % tuple(row2) + newline))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for row in X:<EOL><INDENT>fh.write(asbytes(format % tuple(row) + newline))<EOL><DEDENT><DEDENT>if len(footer) > <NUM_LIT:0>:<EOL><INDENT>footer = footer.replace('<STR_LIT:\n>', '<STR_LIT:\n>' + comments)<EOL>fh.write(asbytes(comments + footer + newline))<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if own_fh:<EOL><INDENT>fh.close()<EOL><DEDENT><DEDENT>

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
    String or character separating columns.
newline : str, optional
    String or character separating lines.

    .. versionadded:: 1.5.0
header : str, optional
    String that will be written at the beginning of the file.

    .. versionadded:: 1.7.0
footer : str, optional
    String that will be written at the end of the file.

    .. versionadded:: 1.7.0
comments : str, optional
    String that will be prepended to the ``header`` and ``footer`` strings,
    to mark them as comments. Default: '# ',  as expected by e.g.
    ``numpy.loadtxt``.

    .. versionadded:: 1.7.0

See Also
--------
save : Save an array to a binary file in NumPy ``.npy`` format
savez : Save several arrays into an uncompressed ``.npz`` archive
savez_compressed : Save several arrays into a compressed ``.npz`` archive

Notes
-----
Further explanation of the `fmt` parameter
(``%[flag]width[.precision]specifier``):

flags:
    ``-`` : left justify

    ``+`` : Forces to precede 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
       <http://docs.python.org/library/string.html#
       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


def genfromtxt(fname, dtype=float, comments='<STR_LIT:#>', delimiter=None,<EOL>skiprows=<NUM_LIT:0>, skip_header=<NUM_LIT:0>, skip_footer=<NUM_LIT:0>, converters=None,<EOL>missing='<STR_LIT>', missing_values=None, filling_values=None,<EOL>usecols=None, names=None,<EOL>excludelist=None, deletechars=None, replace_space='<STR_LIT:_>',<EOL>autostrip=False, case_sensitive=True, defaultfmt="<STR_LIT>",<EOL>unpack=None, usemask=False, loose=True, invalid_raise=True):

<EOL>if comments is not None:<EOL><INDENT>comments = asbytes(comments)<EOL><DEDENT>if isinstance(delimiter, unicode):<EOL><INDENT>delimiter = asbytes(delimiter)<EOL><DEDENT>if isinstance(missing, unicode):<EOL><INDENT>missing = asbytes(missing)<EOL><DEDENT>if isinstance(missing_values, (unicode, list, tuple)):<EOL><INDENT>missing_values = asbytes_nested(missing_values)<EOL><DEDENT>if usemask:<EOL><INDENT>from numpy.ma import MaskedArray, make_mask_descr<EOL><DEDENT>user_converters = converters or {}<EOL>if not isinstance(user_converters, dict):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % type(user_converters))<EOL><DEDENT>own_fhd = False<EOL>try:<EOL><INDENT>if isinstance(fname, basestring):<EOL><INDENT>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:2>:<EOL><INDENT>fhd = iter(np.lib._datasource.open(fname, '<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>fhd = iter(np.lib._datasource.open(fname, '<STR_LIT:rb>'))<EOL><DEDENT>own_fhd = True<EOL><DEDENT>else:<EOL><INDENT>fhd = iter(fname)<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % type(fname))<EOL><DEDENT>split_line = LineSplitter(delimiter=delimiter, comments=comments,<EOL>autostrip=autostrip)._handyman<EOL>validate_names = NameValidator(excludelist=excludelist,<EOL>deletechars=deletechars,<EOL>case_sensitive=case_sensitive,<EOL>replace_space=replace_space)<EOL>if skiprows:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>DeprecationWarning)<EOL>skip_header = skiprows<EOL><DEDENT>for i in range(skip_header):<EOL><INDENT>next(fhd)<EOL><DEDENT>first_values = None<EOL>try:<EOL><INDENT>while not first_values:<EOL><INDENT>first_line = next(fhd)<EOL>if names is True:<EOL><INDENT>if comments in first_line:<EOL><INDENT>first_line = (<EOL>asbytes('<STR_LIT>').join(first_line.split(comments)[<NUM_LIT:1>:]))<EOL><DEDENT><DEDENT>first_values = split_line(first_line)<EOL><DEDENT><DEDENT>except StopIteration:<EOL><INDENT>first_line = asbytes('<STR_LIT>')<EOL>first_values = []<EOL>warnings.warn('<STR_LIT>' % fname)<EOL><DEDENT>if names is True:<EOL><INDENT>fval = first_values[<NUM_LIT:0>].strip()<EOL>if fval in comments:<EOL><INDENT>del first_values[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>if usecols is not None:<EOL><INDENT>try:<EOL><INDENT>usecols = [_.strip() for _ in usecols.split("<STR_LIT:U+002C>")]<EOL><DEDENT>except AttributeError:<EOL><INDENT>try:<EOL><INDENT>usecols = list(usecols)<EOL><DEDENT>except TypeError:<EOL><INDENT>usecols = [usecols, ]<EOL><DEDENT><DEDENT><DEDENT>nbcols = len(usecols or first_values)<EOL>if names is True:<EOL><INDENT>names = validate_names([_bytes_to_name(_.strip())<EOL>for _ in first_values])<EOL>first_line = asbytes('<STR_LIT>')<EOL><DEDENT>elif _is_string_like(names):<EOL><INDENT>names = validate_names([_.strip() for _ in names.split('<STR_LIT:U+002C>')])<EOL><DEDENT>elif names:<EOL><INDENT>names = validate_names(names)<EOL><DEDENT>if dtype is not None:<EOL><INDENT>dtype = easy_dtype(dtype, defaultfmt=defaultfmt, names=names)<EOL><DEDENT>if names is not None:<EOL><INDENT>names = list(names)<EOL><DEDENT>if usecols:<EOL><INDENT>for (i, current) in enumerate(usecols):<EOL><INDENT>if _is_string_like(current):<EOL><INDENT>usecols[i] = names.index(current)<EOL><DEDENT>elif current < <NUM_LIT:0>:<EOL><INDENT>usecols[i] = current + len(first_values)<EOL><DEDENT><DEDENT>if (dtype is not None) and (len(dtype) > nbcols):<EOL><INDENT>descr = dtype.descr<EOL>dtype = np.dtype([descr[_] for _ in usecols])<EOL>names = list(dtype.names)<EOL><DEDENT>elif (names is not None) and (len(names) > nbcols):<EOL><INDENT>names = [names[_] for _ in usecols]<EOL><DEDENT><DEDENT>elif (names is not None) and (dtype is not None):<EOL><INDENT>names = list(dtype.names)<EOL><DEDENT>user_missing_values = missing_values or ()<EOL>missing_values = [list([asbytes('<STR_LIT>')]) for _ in range(nbcols)]<EOL>if isinstance(user_missing_values, dict):<EOL><INDENT>for (key, val) in user_missing_values.items():<EOL><INDENT>if _is_string_like(key):<EOL><INDENT>try:<EOL><INDENT>key = names.index(key)<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if usecols:<EOL><INDENT>try:<EOL><INDENT>key = usecols.index(key)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if isinstance(val, (list, tuple)):<EOL><INDENT>val = [str(_) for _ in val]<EOL><DEDENT>else:<EOL><INDENT>val = [str(val), ]<EOL><DEDENT>if key is None:<EOL><INDENT>for miss in missing_values:<EOL><INDENT>miss.extend(val)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>missing_values[key].extend(val)<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(user_missing_values, (list, tuple)):<EOL><INDENT>for (value, entry) in zip(user_missing_values, missing_values):<EOL><INDENT>value = str(value)<EOL>if value not in entry:<EOL><INDENT>entry.append(value)<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(user_missing_values, bytes):<EOL><INDENT>user_value = user_missing_values.split(asbytes("<STR_LIT:U+002C>"))<EOL>for entry in missing_values:<EOL><INDENT>entry.extend(user_value)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for entry in missing_values:<EOL><INDENT>entry.extend([str(user_missing_values)])<EOL><DEDENT><DEDENT>if missing != asbytes('<STR_LIT>'):<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>DeprecationWarning)<EOL>values = [str(_) for _ in missing.split(asbytes("<STR_LIT:U+002C>"))]<EOL>for entry in missing_values:<EOL><INDENT>entry.extend(values)<EOL><DEDENT><DEDENT>user_filling_values = filling_values<EOL>if user_filling_values is None:<EOL><INDENT>user_filling_values = []<EOL><DEDENT>filling_values = [None] * nbcols<EOL>if isinstance(user_filling_values, dict):<EOL><INDENT>for (key, val) in user_filling_values.items():<EOL><INDENT>if _is_string_like(key):<EOL><INDENT>try:<EOL><INDENT>key = names.index(key)<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if usecols:<EOL><INDENT>try:<EOL><INDENT>key = usecols.index(key)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>filling_values[key] = val<EOL><DEDENT><DEDENT>elif isinstance(user_filling_values, (list, tuple)):<EOL><INDENT>n = len(user_filling_values)<EOL>if (n <= nbcols):<EOL><INDENT>filling_values[:n] = user_filling_values<EOL><DEDENT>else:<EOL><INDENT>filling_values = user_filling_values[:nbcols]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>filling_values = [user_filling_values] * nbcols<EOL><DEDENT>if dtype is None:<EOL><INDENT>converters = [StringConverter(None, missing_values=miss, default=fill)<EOL>for (miss, fill) in zip(missing_values, filling_values)]<EOL><DEDENT>else:<EOL><INDENT>dtype_flat = flatten_dtype(dtype, flatten_base=True)<EOL>if len(dtype_flat) > <NUM_LIT:1>:<EOL><INDENT>zipit = zip(dtype_flat, missing_values, filling_values)<EOL>converters = [StringConverter(dt, locked=True,<EOL>missing_values=miss, default=fill)<EOL>for (dt, miss, fill) in zipit]<EOL><DEDENT>else:<EOL><INDENT>zipit = zip(missing_values, filling_values)<EOL>converters = [StringConverter(dtype, locked=True,<EOL>missing_values=miss, default=fill)<EOL>for (miss, fill) in zipit]<EOL><DEDENT><DEDENT>uc_update = []<EOL>for (j, conv) in user_converters.items():<EOL><INDENT>if _is_string_like(j):<EOL><INDENT>try:<EOL><INDENT>j = names.index(j)<EOL>i = j<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>elif usecols:<EOL><INDENT>try:<EOL><INDENT>i = usecols.index(j)<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>else:<EOL><INDENT>i = j<EOL><DEDENT>if len(first_line):<EOL><INDENT>testing_value = first_values[j]<EOL><DEDENT>else:<EOL><INDENT>testing_value = None<EOL><DEDENT>converters[i].update(conv, locked=True,<EOL>testing_value=testing_value,<EOL>default=filling_values[i],<EOL>missing_values=missing_values[i],)<EOL>uc_update.append((i, conv))<EOL><DEDENT>user_converters.update(uc_update)<EOL>rows = []<EOL>append_to_rows = rows.append<EOL>if usemask:<EOL><INDENT>masks = []<EOL>append_to_masks = masks.append<EOL><DEDENT>invalid = []<EOL>append_to_invalid = invalid.append<EOL>for (i, line) in enumerate(itertools.chain([first_line, ], fhd)):<EOL><INDENT>values = split_line(line)<EOL>nbvalues = len(values)<EOL>if nbvalues == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>if usecols:<EOL><INDENT>try:<EOL><INDENT>values = [values[_] for _ in usecols]<EOL><DEDENT>except IndexError:<EOL><INDENT>append_to_invalid((i + skip_header + <NUM_LIT:1>, nbvalues))<EOL>continue<EOL><DEDENT><DEDENT>elif nbvalues != nbcols:<EOL><INDENT>append_to_invalid((i + skip_header + <NUM_LIT:1>, nbvalues))<EOL>continue<EOL><DEDENT>append_to_rows(tuple(values))<EOL>if usemask:<EOL><INDENT>append_to_masks(tuple([v.strip() in m<EOL>for (v, m) in zip(values, missing_values)]))<EOL><DEDENT><DEDENT>if own_fhd:<EOL><INDENT>fhd.close()<EOL><DEDENT>if dtype is None:<EOL><INDENT>for (i, converter) in enumerate(converters):<EOL><INDENT>current_column = [itemgetter(i)(_m) for _m in rows]<EOL>try:<EOL><INDENT>converter.iterupgrade(current_column)<EOL><DEDENT>except ConverterLockError:<EOL><INDENT>errmsg = "<STR_LIT>" % i<EOL>current_column = map(itemgetter(i), rows)<EOL>for (j, value) in enumerate(current_column):<EOL><INDENT>try:<EOL><INDENT>converter.upgrade(value)<EOL><DEDENT>except (ConverterError, ValueError):<EOL><INDENT>errmsg += "<STR_LIT>"<EOL>errmsg %= (j + <NUM_LIT:1> + skip_header, value)<EOL>raise ConverterError(errmsg)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>nbinvalid = len(invalid)<EOL>if nbinvalid > <NUM_LIT:0>:<EOL><INDENT>nbrows = len(rows) + nbinvalid - skip_footer<EOL>template = "<STR_LIT>" % nbcols<EOL>if skip_footer > <NUM_LIT:0>:<EOL><INDENT>nbinvalid_skipped = len([_ for _ in invalid<EOL>if _[<NUM_LIT:0>] > nbrows + skip_header])<EOL>invalid = invalid[:nbinvalid - nbinvalid_skipped]<EOL>skip_footer -= nbinvalid_skipped<EOL><INDENT>nbrows -= skip_footer<EOL>errmsg = [template % (i, nb)<EOL>for (i, nb) in invalid if i < nbrows]<EOL>

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_rows : int, optional
    `skip_rows` was deprecated in numpy 1.5, and will be removed in
    numpy 2.0. Please use `skip_header` instead.
skip_header : int, optional
    The number of lines to skip at the beginning of the file.
skip_footer : int, optional
    The number of lines to skip at the end of the file.
converters : variable, optional
    The set of functions that convert the data of a column to a value.
    The converters can also be used to provide a default value
    for missing data: ``converters = {3: lambda s: float(s or 0)}``.
missing : variable, optional
    `missing` was deprecated in numpy 1.5, and will be removed in
    numpy 2.0. Please use `missing_values` instead.
missing_values : variable, optional
    The set of strings corresponding to missing data.
filling_values : variable, optional
    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.
loose : bool, optional
    If True, do not raise errors for invalid values.
invalid_raise : bool, optional
    If True, an exception is raised if an inconsistency is detected in the
    number of columns.
    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
       <http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html>`_.

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', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])

Using dtype = None

>>> 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', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])

Specifying dtype and names

>>> s.seek(0)
>>> data = np.genfromtxt(s, dtype="i8,f8,S5",
... names=['myint','myfloat','mystring'], delimiter=",")
>>> data
array((1, 1.3, 'abcde'),
      dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])

An example with fixed-width columns

>>> 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', '<i8'), ('fltvar', '<f8'), ('strvar', '|S5')])


kwargs['<STR_LIT>'] = False<EOL>return genfromtxt(fname, **kwargs)<EOL>

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.


def loadtxt(fname, dtype=float, comments='<STR_LIT:#>', delimiter=None,<EOL>converters=None, skiprows=<NUM_LIT:0>, usecols=None, unpack=False,<EOL>ndmin=<NUM_LIT:0>):

<EOL>if comments is not None:<EOL><INDENT>comments = asbytes(comments)<EOL><DEDENT>user_converters = converters<EOL>if delimiter is not None:<EOL><INDENT>delimiter = asbytes(delimiter)<EOL><DEDENT>if usecols is not None:<EOL><INDENT>usecols = list(usecols)<EOL><DEDENT>fown = False<EOL>try:<EOL><INDENT>if _is_string_like(fname):<EOL><INDENT>fown = True<EOL>if fname.endswith('<STR_LIT>'):<EOL><INDENT>fh = iter(seek_gzip_factory(fname))<EOL><DEDENT>elif fname.endswith('<STR_LIT>'):<EOL><INDENT>import bz2<EOL>fh = iter(bz2.BZ2File(fname))<EOL><DEDENT>elif sys.version_info[<NUM_LIT:0>] == <NUM_LIT:2>:<EOL><INDENT>fh = iter(open(fname, '<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>fh = iter(open(fname))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>fh = iter(fname)<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>X = []<EOL>def flatten_dtype(dt):<EOL><INDENT>"""<STR_LIT>"""<EOL>if dt.names is None:<EOL><INDENT>shape = dt.shape<EOL>if len(shape) == <NUM_LIT:0>:<EOL><INDENT>return ([dt.base], None)<EOL><DEDENT>else:<EOL><INDENT>packing = [(shape[-<NUM_LIT:1>], list)]<EOL>if len(shape) > <NUM_LIT:1>:<EOL><INDENT>for dim in dt.shape[-<NUM_LIT:2>::-<NUM_LIT:1>]:<EOL><INDENT>packing = [(dim*packing[<NUM_LIT:0>][<NUM_LIT:0>], packing*dim)]<EOL><DEDENT><DEDENT>return ([dt.base] * int(np.prod(dt.shape)), packing)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>types = []<EOL>packing = []<EOL>for field in dt.names:<EOL><INDENT>tp, bytes = dt.fields[field]<EOL>flat_dt, flat_packing = flatten_dtype(tp)<EOL>types.extend(flat_dt)<EOL>if len(tp.shape) > <NUM_LIT:0>:<EOL><INDENT>packing.extend(flat_packing)<EOL><DEDENT>else:<EOL><INDENT>packing.append((len(flat_dt), flat_packing))<EOL><DEDENT><DEDENT>return (types, packing)<EOL><DEDENT><DEDENT>def pack_items(items, packing):<EOL><INDENT>"""<STR_LIT>"""<EOL>if packing is None:<EOL><INDENT>return items[<NUM_LIT:0>]<EOL><DEDENT>elif packing is tuple:<EOL><INDENT>return tuple(items)<EOL><DEDENT>elif packing is list:<EOL><INDENT>return list(items)<EOL><DEDENT>else:<EOL><INDENT>start = <NUM_LIT:0><EOL>ret = []<EOL>for length, subpacking in packing:<EOL><INDENT>ret.append(pack_items(items[start:start+length], subpacking))<EOL>start += length<EOL><DEDENT>return tuple(ret)<EOL><DEDENT><DEDENT>def split_line(line):<EOL><INDENT>"""<STR_LIT>"""<EOL>if comments is None:<EOL><INDENT>line = asbytes(line).strip(asbytes('<STR_LIT:\r\n>'))<EOL><DEDENT>else:<EOL><INDENT>line = asbytes(line).split(comments)[<NUM_LIT:0>].strip(asbytes('<STR_LIT:\r\n>'))<EOL><DEDENT>if line:<EOL><INDENT>return line.split(delimiter)<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT><DEDENT>try:<EOL><INDENT>dtype = np.dtype(dtype)<EOL>defconv = _getconv(dtype)<EOL>for i in range(skiprows):<EOL><INDENT>next(fh)<EOL><DEDENT>first_vals = None<EOL>try:<EOL><INDENT>while not first_vals:<EOL><INDENT>first_line = next(fh)<EOL>first_vals = split_line(first_line)<EOL><DEDENT><DEDENT>except StopIteration:<EOL><INDENT>first_line = '<STR_LIT>'<EOL>first_vals = []<EOL>warnings.warn('<STR_LIT>' % fname)<EOL><DEDENT>N = len(usecols or first_vals)<EOL>dtype_types, packing = flatten_dtype(dtype)<EOL>if len(dtype_types) > <NUM_LIT:1>:<EOL><INDENT>converters = [_getconv(dt) for dt in dtype_types]<EOL><DEDENT>else:<EOL><INDENT>converters = [defconv for i in range(N)]<EOL>if N > <NUM_LIT:1>:<EOL><INDENT>packing = [(N, tuple)]<EOL><DEDENT><DEDENT>for i, conv in (user_converters or {}).items():<EOL><INDENT>if usecols:<EOL><INDENT>try:<EOL><INDENT>i = usecols.index(i)<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>converters[i] = conv<EOL><DEDENT>for i, line in enumerate(itertools.chain([first_line], fh)):<EOL><INDENT>vals = split_line(line)<EOL>if len(vals) == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>if usecols:<EOL><INDENT>vals = [vals[i] for i in usecols]<EOL><DEDENT>if len(vals) != N:<EOL><INDENT>line_num = i + skiprows + <NUM_LIT:1><EOL>raise ValueError("<STR_LIT>"<EOL>% line_num)<EOL><DEDENT>items = [conv(val) for (conv, val) in zip(converters, vals)]<EOL>items = pack_items(items, packing)<EOL>X.append(items)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if fown:<EOL><INDENT>fh.close()<EOL><DEDENT><DEDENT>X = np.array(X, dtype)<EOL>if X.ndim == <NUM_LIT:3> and X.shape[:<NUM_LIT:2>] == (<NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>X.shape = (<NUM_LIT:1>, -<NUM_LIT:1>)<EOL><DEDENT>if ndmin not in [<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>]:<EOL><INDENT>raise ValueError('<STR_LIT>' % ndmin)<EOL><DEDENT>if X.ndim > ndmin:<EOL><INDENT>X = np.squeeze(X)<EOL><DEDENT>if X.ndim < ndmin:<EOL><INDENT>if ndmin == <NUM_LIT:1>:<EOL><INDENT>X = np.atleast_1d(X)<EOL><DEDENT>elif ndmin == <NUM_LIT:2>:<EOL><INDENT>X = np.atleast_2d(X).T<EOL><DEDENT><DEDENT>if unpack:<EOL><INDENT>if len(dtype_types) > <NUM_LIT:1>:<EOL><INDENT>return [X[field] for field in dtype.names]<EOL><DEDENT>else:<EOL><INDENT>return X.T<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return X<EOL><DEDENT>

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', '<i4'), ('weight', '<f4')])

>>> 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.])


x = nx.asanyarray(x)<EOL>y1 = nx.floor(x)<EOL>y2 = nx.ceil(x)<EOL>if y is None:<EOL><INDENT>y = nx.asanyarray(y1)<EOL><DEDENT>y[...] = nx.where(x >= <NUM_LIT:0>, y1, y2)<EOL>return y<EOL>

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.])


if y is None:<EOL><INDENT>x = nx.asarray(x)<EOL>y = nx.empty(x.shape, dtype=nx.bool_)<EOL><DEDENT>nx.logical_and(nx.isinf(x), nx.signbit(x), y)<EOL>return y<EOL>

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])


def _write_array_header(fp, d, version=None):

import struct<EOL>header = ["<STR_LIT:{>"]<EOL>for key, value in sorted(d.items()):<EOL><INDENT>header.append("<STR_LIT>" % (key, repr(value)))<EOL><DEDENT>header.append("<STR_LIT:}>")<EOL>header = "<STR_LIT>".join(header)<EOL>current_header_len = MAGIC_LEN + <NUM_LIT:2> + len(header) + <NUM_LIT:1>  <EOL>topad = <NUM_LIT:16> - (current_header_len % <NUM_LIT:16>)<EOL>header = header + '<STR_LIT:U+0020>'*topad + '<STR_LIT:\n>'<EOL>header = asbytes(_filter_header(header))<EOL>if len(header) >= (<NUM_LIT>*<NUM_LIT>) and version == (<NUM_LIT:1>, <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % (<NUM_LIT>*<NUM_LIT>))<EOL><DEDENT>if len(header) < (<NUM_LIT>*<NUM_LIT>):<EOL><INDENT>header_len_str = struct.pack('<STR_LIT>', len(header))<EOL>version = (<NUM_LIT:1>, <NUM_LIT:0>)<EOL><DEDENT>elif len(header) < (<NUM_LIT:2>**<NUM_LIT:32>):<EOL><INDENT>header_len_str = struct.pack('<STR_LIT>', len(header))<EOL>version = (<NUM_LIT:2>, <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>fp.write(magic(*version))<EOL>fp.write(header_len_str)<EOL>fp.write(header)<EOL>return version<EOL>

Write the header for an array and returns the version used

    Parameters
    ----------
    fp : filelike object
    d : dict
        This has the appropriate entries for writing its string representation
        to the header of the file.
    version: tuple or None
        None means use oldest that works
        explicit version will raise a ValueError if the format does not
        allow saving this data.  Default: None
    Returns
    -------
    version : tuple of int
        the file version which needs to be used to store the data


_write_array_header(fp, d, (<NUM_LIT:1>, <NUM_LIT:0>))<EOL>

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.


_read_array_header(fp, version=(<NUM_LIT:1>, <NUM_LIT:0>))<EOL>

Read an array header from a filelike object using the 1.0 file format
version.

This will leave the file object located just after the header.

Parameters
----------
fp : filelike object
    A file object or something with a `.read()` method like a file.

Returns
-------
shape : tuple of int
    The shape of the array.
fortran_order : bool
    The array data will be written out directly if it is either
    C-contiguous or Fortran-contiguous. Otherwise, it will be made
    contiguous before writing it out.
dtype : dtype
    The dtype of the file's data.

Raises
------
ValueError
    If the data is invalid.


_read_array_header(fp, version=(<NUM_LIT:2>, <NUM_LIT:0>))<EOL>

Read an array header from a filelike object using the 2.0 file format
version.

This will leave the file object located just after the header.

.. versionadded:: 1.9.0

Parameters
----------
fp : filelike object
    A file object or something with a `.read()` method like a file.

Returns
-------
shape : tuple of int
    The shape of the array.
fortran_order : bool
    The array data will be written out directly if it is either
    C-contiguous or Fortran-contiguous. Otherwise, it will be made
    contiguous before writing it out.
dtype : dtype
    The dtype of the file's data.

Raises
------
ValueError
    If the data is invalid.


if dtype.names is not None:<EOL><INDENT>return dtype.descr<EOL><DEDENT>else:<EOL><INDENT>return dtype.str<EOL><DEDENT>

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.


def open_memmap(filename, mode='<STR_LIT>', dtype=None, shape=None,<EOL>fortran_order=False, version=None):

if not isinstance(filename, basestring):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if '<STR_LIT:w>' in mode:<EOL><INDENT>_check_version(version)<EOL>dtype = numpy.dtype(dtype)<EOL>if dtype.hasobject:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>d = dict(<EOL>descr=dtype_to_descr(dtype),<EOL>fortran_order=fortran_order,<EOL>shape=shape,<EOL>)<EOL>fp = open(filename, mode+'<STR_LIT:b>')<EOL>try:<EOL><INDENT>used_ver = _write_array_header(fp, d, version)<EOL>if version != (<NUM_LIT:2>, <NUM_LIT:0>) and used_ver == (<NUM_LIT:2>, <NUM_LIT:0>):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>", UserWarning)<EOL><DEDENT>offset = fp.tell()<EOL><DEDENT>finally:<EOL><INDENT>fp.close()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>fp = open(filename, '<STR_LIT:rb>')<EOL>try:<EOL><INDENT>version = read_magic(fp)<EOL>_check_version(version)<EOL>shape, fortran_order, dtype = _read_array_header(fp, version)<EOL>if dtype.hasobject:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>offset = fp.tell()<EOL><DEDENT>finally:<EOL><INDENT>fp.close()<EOL><DEDENT><DEDENT>if fortran_order:<EOL><INDENT>order = '<STR_LIT:F>'<EOL><DEDENT>else:<EOL><INDENT>order = '<STR_LIT:C>'<EOL><DEDENT>if mode == '<STR_LIT>':<EOL><INDENT>mode = '<STR_LIT>'<EOL><DEDENT>marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order,<EOL>mode=mode, offset=offset)<EOL>return marray<EOL>

Open a .npy file as a memory-mapped array.

This may be used to read an existing file or create a new one.

Parameters
----------
filename : str
    The name of the file on disk.  This may *not* be a file-like
    object.
mode : str, optional
    The mode in which to open the file; the default is 'r+'.  In
    addition to the standard file modes, 'c' is also accepted to mean
    "copy on write."  See `memmap` for the available mode strings.
dtype : data-type, optional
    The data type of the array if we are creating a new file in "write"
    mode, if not, `dtype` is ignored.  The default value is None, which
    results in a data-type of `float64`.
shape : tuple of int
    The shape of the array if we are creating a new file in "write"
    mode, in which case this parameter is required.  Otherwise, this
    parameter is ignored and is thus optional.
fortran_order : bool, optional
    Whether the array should be Fortran-contiguous (True) or
    C-contiguous (False, the default) if we are creating a new file in
    "write" mode.
version : tuple of int (major, minor) or None
    If the mode is a "write" mode, then this is the version of the file
    format used to create the file.  None means use the oldest
    supported version that is able to store the data.  Default: None

Returns
-------
marray : memmap
    The memory-mapped array.

Raises
------
ValueError
    If the data or the mode is invalid.
IOError
    If the file is not found or cannot be opened correctly.

See Also
--------
memmap


def write_array(fp, array, version=None):

_check_version(version)<EOL>used_ver = _write_array_header(fp, header_data_from_array_1_0(array),<EOL>version)<EOL>if version != (<NUM_LIT:2>, <NUM_LIT:0>) and used_ver == (<NUM_LIT:2>, <NUM_LIT:0>):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>", UserWarning)<EOL><DEDENT>buffersize = max(<NUM_LIT:16> * <NUM_LIT> ** <NUM_LIT:2> // array.itemsize, <NUM_LIT:1>)<EOL>if array.dtype.hasobject:<EOL><INDENT>pickle.dump(array, fp, protocol=<NUM_LIT:2>)<EOL><DEDENT>elif array.flags.f_contiguous and not array.flags.c_contiguous:<EOL><INDENT>if isfileobj(fp):<EOL><INDENT>array.T.tofile(fp)<EOL><DEDENT>else:<EOL><INDENT>for chunk in numpy.nditer(<EOL>array, flags=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>buffersize=buffersize, order='<STR_LIT:F>'):<EOL><INDENT>fp.write(chunk.tobytes('<STR_LIT:C>'))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if isfileobj(fp):<EOL><INDENT>array.tofile(fp)<EOL><DEDENT>else:<EOL><INDENT>for chunk in numpy.nditer(<EOL>array, flags=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>buffersize=buffersize, order='<STR_LIT:C>'):<EOL><INDENT>fp.write(chunk.tobytes('<STR_LIT:C>'))<EOL><DEDENT><DEDENT><DEDENT>

Write an array to an NPY file, including a header.

If the array is neither C-contiguous nor Fortran-contiguous AND the
file_like object is not a real file object, this function will have to
copy data in memory.

Parameters
----------
fp : file_like object
    An open, writable file object, or similar object with a
    ``.write()`` method.
array : ndarray
    The array to write to disk.
version : (int, int) or None, optional
    The version number of the format. None means use the oldest
    supported version that is able to store the data.  Default: None

Raises
------
ValueError
    If the array cannot be persisted.
Various other errors
    If the array contains Python objects as part of its dtype, the
    process of pickling them may raise various errors if the objects
    are not picklable.


<EOL>import struct<EOL>if version == (<NUM_LIT:1>, <NUM_LIT:0>):<EOL><INDENT>hlength_str = _read_bytes(fp, <NUM_LIT:2>, "<STR_LIT>")<EOL>header_length = struct.unpack('<STR_LIT>', hlength_str)[<NUM_LIT:0>]<EOL>header = _read_bytes(fp, header_length, "<STR_LIT>")<EOL><DEDENT>elif version == (<NUM_LIT:2>, <NUM_LIT:0>):<EOL><INDENT>hlength_str = _read_bytes(fp, <NUM_LIT:4>, "<STR_LIT>")<EOL>header_length = struct.unpack('<STR_LIT>', hlength_str)[<NUM_LIT:0>]<EOL>header = _read_bytes(fp, header_length, "<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % version)<EOL><DEDENT>header = _filter_header(header)<EOL>try:<EOL><INDENT>d = safe_eval(header)<EOL><DEDENT>except SyntaxError as e:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % (header, e))<EOL><DEDENT>if not isinstance(d, dict):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % d)<EOL><DEDENT>keys = sorted(d.keys())<EOL>if keys != ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % (keys,))<EOL><DEDENT>if (not isinstance(d['<STR_LIT>'], tuple) or<EOL>not numpy.all([isinstance(x, (int, long)) for x in d['<STR_LIT>']])):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % (d['<STR_LIT>'],))<EOL><DEDENT>if not isinstance(d['<STR_LIT>'], bool):<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % (d['<STR_LIT>'],))<EOL><DEDENT>try:<EOL><INDENT>dtype = numpy.dtype(d['<STR_LIT>'])<EOL><DEDENT>except TypeError as e:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % (d['<STR_LIT>'],))<EOL><DEDENT>return d['<STR_LIT>'], d['<STR_LIT>'], dtype<EOL>


truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))<EOL>a1, a2 = poly1d(a1), poly1d(a2)<EOL>val = NX.convolve(a1, a2)<EOL>if truepoly:<EOL><INDENT>val = poly1d(val)<EOL><DEDENT>return val<EOL>

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
convolve : Array convolution. Same output as polymul, but has parameter
           for overlap mode.

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


<EOL>p = atleast_1d(p)<EOL>if len(p.shape) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>non_zero = NX.nonzero(NX.ravel(p))[<NUM_LIT:0>]<EOL>if len(non_zero) == <NUM_LIT:0>:<EOL><INDENT>return NX.array([])<EOL><DEDENT>trailing_zeros = len(p) - non_zero[-<NUM_LIT:1>] - <NUM_LIT:1><EOL>p = p[int(non_zero[<NUM_LIT:0>]):int(non_zero[-<NUM_LIT:1>])+<NUM_LIT:1>]<EOL>if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)):<EOL><INDENT>p = p.astype(float)<EOL><DEDENT>N = len(p)<EOL>if N > <NUM_LIT:1>:<EOL><INDENT>A = diag(NX.ones((N-<NUM_LIT:2>,), p.dtype), -<NUM_LIT:1>)<EOL>A[<NUM_LIT:0>,:] = -p[<NUM_LIT:1>:] / p[<NUM_LIT:0>]<EOL>roots = eigvals(A)<EOL><DEDENT>else:<EOL><INDENT>roots = NX.array([])<EOL><DEDENT>roots = hstack((roots, NX.zeros(trailing_zeros, roots.dtype)))<EOL>return roots<EOL>

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])


p = NX.asarray(p)<EOL>if isinstance(x, poly1d):<EOL><INDENT>y = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>x = NX.asarray(x)<EOL>y = NX.zeros_like(x)<EOL><DEDENT>for i in range(len(p)):<EOL><INDENT>y = x * y + p[i]<EOL><DEDENT>return y<EOL>

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.])


seq_of_zeros = atleast_1d(seq_of_zeros)<EOL>sh = seq_of_zeros.shape<EOL>if len(sh) == <NUM_LIT:2> and sh[<NUM_LIT:0>] == sh[<NUM_LIT:1>] and sh[<NUM_LIT:0>] != <NUM_LIT:0>:<EOL><INDENT>seq_of_zeros = eigvals(seq_of_zeros)<EOL><DEDENT>elif len(sh) == <NUM_LIT:1>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(seq_of_zeros) == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:1.0><EOL><DEDENT>a = [<NUM_LIT:1>]<EOL>for k in range(len(seq_of_zeros)):<EOL><INDENT>a = NX.convolve(a, [<NUM_LIT:1>, -seq_of_zeros[k]], mode='<STR_LIT>')<EOL><DEDENT>if issubclass(a.dtype.type, NX.complexfloating):<EOL><INDENT>roots = NX.asarray(seq_of_zeros, complex)<EOL>pos_roots = sort_complex(NX.compress(roots.imag > <NUM_LIT:0>, roots))<EOL>neg_roots = NX.conjugate(sort_complex(<EOL>NX.compress(roots.imag < <NUM_LIT:0>, roots)))<EOL>if (len(pos_roots) == len(neg_roots) and<EOL>NX.alltrue(neg_roots == pos_roots)):<EOL><INDENT>a = a.real.copy()<EOL><DEDENT><DEDENT>return a<EOL>

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.


def integ(self, m=<NUM_LIT:1>, k=<NUM_LIT:0>):

return poly1d(polyint(self.coeffs, m=m, k=k))<EOL>

Return an antiderivative (indefinite integral) of this polynomial.

Refer to `polyint` for full documentation.

See Also
--------
polyint : equivalent function


m = int(m)<EOL>if m < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>truepoly = isinstance(p, poly1d)<EOL>p = NX.asarray(p)<EOL>n = len(p) - <NUM_LIT:1><EOL>y = p[:-<NUM_LIT:1>] * NX.arange(n, <NUM_LIT:0>, -<NUM_LIT:1>)<EOL>if m == <NUM_LIT:0>:<EOL><INDENT>val = p<EOL><DEDENT>else:<EOL><INDENT>val = polyder(y, m - <NUM_LIT:1>)<EOL><DEDENT>if truepoly:<EOL><INDENT>val = poly1d(val)<EOL><DEDENT>return val<EOL>

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.])


def find_duplicates(a, key=None, ignoremask=True, return_index=False):

a = np.asanyarray(a).ravel()<EOL>fields = get_fieldstructure(a.dtype)<EOL>base = a<EOL>if key:<EOL><INDENT>for f in fields[key]:<EOL><INDENT>base = base[f]<EOL><DEDENT>base = base[key]<EOL><DEDENT>sortidx = base.argsort()<EOL>sortedbase = base[sortidx]<EOL>sorteddata = sortedbase.filled()<EOL>flag = (sorteddata[:-<NUM_LIT:1>] == sorteddata[<NUM_LIT:1>:])<EOL>if ignoremask:<EOL><INDENT>sortedmask = sortedbase.recordmask<EOL>flag[sortedmask[<NUM_LIT:1>:]] = False<EOL><DEDENT>flag = np.concatenate(([False], flag))<EOL>flag[:-<NUM_LIT:1>] = flag[:-<NUM_LIT:1>] + flag[<NUM_LIT:1>:]<EOL>duplicates = a[sortidx][flag]<EOL>if return_index:<EOL><INDENT>return (duplicates, sortidx[flag])<EOL><DEDENT>else:<EOL><INDENT>return duplicates<EOL><DEDENT>

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


def izip_records(seqarrays, fill_value=None, flatten=True):

<EOL>def sentinel(counter=([fill_value] * (len(seqarrays) - <NUM_LIT:1>)).pop):<EOL><INDENT>"<STR_LIT>"<EOL>yield counter()<EOL><DEDENT>fillers = itertools.repeat(fill_value)<EOL>iters = [itertools.chain(it, sentinel(), fillers) for it in seqarrays]<EOL>if flatten:<EOL><INDENT>zipfunc = _izip_fields_flat<EOL><DEDENT>else:<EOL><INDENT>zipfunc = _izip_fields<EOL><DEDENT>try:<EOL><INDENT>for tup in zip(*iters):<EOL><INDENT>yield tuple(zipfunc(tup))<EOL><DEDENT><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>

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


def rec_join(key, r1, r2, jointype='<STR_LIT>', r1postfix='<STR_LIT:1>', r2postfix='<STR_LIT:2>',<EOL>defaults=None):

kwargs = dict(jointype=jointype, r1postfix=r1postfix, r2postfix=r2postfix,<EOL>defaults=defaults, usemask=False, asrecarray=True)<EOL>return join_by(key, r1, r2, **kwargs)<EOL>

Join arrays `r1` and `r2` on keys.
Alternative to join_by, that always returns a np.recarray.

See Also
--------
join_by : equivalent function


newdtype = []<EOL>if flatten:<EOL><INDENT>for a in seqarrays:<EOL><INDENT>newdtype.extend(flatten_descr(a.dtype))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for a in seqarrays:<EOL><INDENT>current = a.dtype<EOL>names = current.names or ()<EOL>if len(names) > <NUM_LIT:1>:<EOL><INDENT>newdtype.append(('<STR_LIT>', current.descr))<EOL><DEDENT>else:<EOL><INDENT>newdtype.extend(current.descr)<EOL><DEDENT><DEDENT><DEDENT>return np.dtype(newdtype).descr<EOL>

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.


def join_by(key, r1, r2, jointype='<STR_LIT>', r1postfix='<STR_LIT:1>', r2postfix='<STR_LIT:2>',<EOL>defaults=None, usemask=True, asrecarray=False):

<EOL>if jointype not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % jointype<EOL>)<EOL><DEDENT>if isinstance(key, basestring):<EOL><INDENT>key = (key,)<EOL><DEDENT>for name in key:<EOL><INDENT>if name not in r1.dtype.names:<EOL><INDENT>raise ValueError('<STR_LIT>' % name)<EOL><DEDENT>if name not in r2.dtype.names:<EOL><INDENT>raise ValueError('<STR_LIT>' % name)<EOL><DEDENT><DEDENT>r1 = r1.ravel()<EOL>r2 = r2.ravel()<EOL>nb1 = len(r1)<EOL>(r1names, r2names) = (r1.dtype.names, r2.dtype.names)<EOL>if (set.intersection(set(r1names), set(r2names)).difference(key) and<EOL>not (r1postfix or r2postfix)):<EOL><INDENT>msg = "<STR_LIT>"<EOL>msg += "<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>r1k = drop_fields(r1, [n for n in r1names if n not in key])<EOL>r2k = drop_fields(r2, [n for n in r2names if n not in key])<EOL>aux = ma.concatenate((r1k, r2k))<EOL>idx_sort = aux.argsort(order=key)<EOL>aux = aux[idx_sort]<EOL>flag_in = ma.concatenate(([False], aux[<NUM_LIT:1>:] == aux[:-<NUM_LIT:1>]))<EOL>flag_in[:-<NUM_LIT:1>] = flag_in[<NUM_LIT:1>:] + flag_in[:-<NUM_LIT:1>]<EOL>idx_in = idx_sort[flag_in]<EOL>idx_1 = idx_in[(idx_in < nb1)]<EOL>idx_2 = idx_in[(idx_in >= nb1)] - nb1<EOL>(r1cmn, r2cmn) = (len(idx_1), len(idx_2))<EOL>if jointype == '<STR_LIT>':<EOL><INDENT>(r1spc, r2spc) = (<NUM_LIT:0>, <NUM_LIT:0>)<EOL><DEDENT>elif jointype == '<STR_LIT>':<EOL><INDENT>idx_out = idx_sort[~flag_in]<EOL>idx_1 = np.concatenate((idx_1, idx_out[(idx_out < nb1)]))<EOL>idx_2 = np.concatenate((idx_2, idx_out[(idx_out >= nb1)] - nb1))<EOL>(r1spc, r2spc) = (len(idx_1) - r1cmn, len(idx_2) - r2cmn)<EOL><DEDENT>elif jointype == '<STR_LIT>':<EOL><INDENT>idx_out = idx_sort[~flag_in]<EOL>idx_1 = np.concatenate((idx_1, idx_out[(idx_out < nb1)]))<EOL>(r1spc, r2spc) = (len(idx_1) - r1cmn, <NUM_LIT:0>)<EOL><DEDENT>(s1, s2) = (r1[idx_1], r2[idx_2])<EOL>ndtype = [list(_) for _ in r1k.dtype.descr]<EOL>ndtype.extend(list(_) for _ in r1.dtype.descr if _[<NUM_LIT:0>] not in key)<EOL>names = list(_[<NUM_LIT:0>] for _ in ndtype)<EOL>for desc in r2.dtype.descr:<EOL><INDENT>desc = list(desc)<EOL>name = desc[<NUM_LIT:0>]<EOL>if name in names:<EOL><INDENT>nameidx = ndtype.index(desc)<EOL>current = ndtype[nameidx]<EOL>if name in key:<EOL><INDENT>current[-<NUM_LIT:1>] = max(desc[<NUM_LIT:1>], current[-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>current[<NUM_LIT:0>] += r1postfix<EOL>desc[<NUM_LIT:0>] += r2postfix<EOL>ndtype.insert(nameidx + <NUM_LIT:1>, desc)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>names.extend(desc[<NUM_LIT:0>])<EOL>ndtype.append(desc)<EOL><DEDENT><DEDENT>ndtype = [tuple(_) for _ in ndtype]<EOL>cmn = max(r1cmn, r2cmn)<EOL>output = ma.masked_all((cmn + r1spc + r2spc,), dtype=ndtype)<EOL>names = output.dtype.names<EOL>for f in r1names:<EOL><INDENT>selected = s1[f]<EOL>if f not in names or (f in r2names and not r2postfix and f not in key):<EOL><INDENT>f += r1postfix<EOL><DEDENT>current = output[f]<EOL>current[:r1cmn] = selected[:r1cmn]<EOL>if jointype in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>current[cmn:cmn + r1spc] = selected[r1cmn:]<EOL><DEDENT><DEDENT>for f in r2names:<EOL><INDENT>selected = s2[f]<EOL>if f not in names or (f in r1names and not r1postfix and f not in key):<EOL><INDENT>f += r2postfix<EOL><DEDENT>current = output[f]<EOL>current[:r2cmn] = selected[:r2cmn]<EOL>if (jointype == '<STR_LIT>') and r2spc:<EOL><INDENT>current[-r2spc:] = selected[r2cmn:]<EOL><DEDENT><DEDENT>output.sort(order=key)<EOL>kwargs = dict(usemask=usemask, asrecarray=asrecarray)<EOL>return _fix_output(_fix_defaults(output, defaults), **kwargs)<EOL>

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...


names = output.dtype.names<EOL>(data, mask, fill_value) = (output.data, output.mask, output.fill_value)<EOL>for (k, v) in (defaults or {}).items():<EOL><INDENT>if k in names:<EOL><INDENT>fill_value[k] = v<EOL>data[k][mask[k]] = v<EOL><DEDENT><DEDENT>return output<EOL>

Update the fill_value and masked data of `output`
from the default given in a dictionary defaults.


def diff(a, n=<NUM_LIT:1>, axis=-<NUM_LIT:1>):

if n == <NUM_LIT:0>:<EOL><INDENT>return a<EOL><DEDENT>if n < <NUM_LIT:0>:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" + repr(n))<EOL><DEDENT>a = asanyarray(a)<EOL>nd = len(a.shape)<EOL>slice1 = [slice(None)]*nd<EOL>slice2 = [slice(None)]*nd<EOL>slice1[axis] = slice(<NUM_LIT:1>, None)<EOL>slice2[axis] = slice(None, -<NUM_LIT:1>)<EOL>slice1 = tuple(slice1)<EOL>slice2 = tuple(slice2)<EOL>if n > <NUM_LIT:1>:<EOL><INDENT>return diff(a[slice1]-a[slice2], n-<NUM_LIT:1>, axis=axis)<EOL><DEDENT>else:<EOL><INDENT>return a[slice1]-a[slice2]<EOL><DEDENT>

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]])


def median(a, axis=None, out=None, overwrite_input=False, keepdims=False):

r, k = _ureduce(a, func=_median, axis=axis, out=out,<EOL>overwrite_input=overwrite_input)<EOL>if keepdims:<EOL><INDENT>return r.reshape(k)<EOL><DEDENT>else:<EOL><INDENT>return r<EOL><DEDENT>

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 or sequence of int, optional
    Axis along which the medians are computed. The default (axis=None)
    is to compute the median along a flattened version of the array.
    A sequence of axes is supported since version 1.9.0.
out : ndarray, optional
    Alternative output array in which to place the result. It must have
    the same shape and buffer length as the expected output, but the
    type (of the output) will be cast if necessary.
overwrite_input : bool, optional
   If True, then allow use of memory of input array (a) for
   calculations. The input array will be modified by the call to
   median. This will save memory when you do not need to preserve the
   contents of the input array. Treat the input as undefined, but it
   will probably be fully or partially sorted. Default is False. Note
   that, if `overwrite_input` is True and the input is not already an
   ndarray, an error will be raised.
keepdims : bool, optional
    If this is set to True, the axes which are reduced are left
    in the result as dimensions with size one. With this option,
    the result will broadcast correctly against the original `arr`.

    .. versionadded:: 1.9.0

Returns
-------
median : ndarray
    A new array holding the result (unless `out` is specified, in which
    case that array is returned instead).  If the input contains
    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)


def percentile(a, q, axis=None, out=None,<EOL>overwrite_input=False, interpolation='<STR_LIT>', keepdims=False):

q = array(q, dtype=np.float64, copy=True)<EOL>r, k = _ureduce(a, func=_percentile, q=q, axis=axis, out=out,<EOL>overwrite_input=overwrite_input,<EOL>interpolation=interpolation)<EOL>if keepdims:<EOL><INDENT>if q.ndim == <NUM_LIT:0>:<EOL><INDENT>return r.reshape(k)<EOL><DEDENT>else:<EOL><INDENT>return r.reshape([len(q)] + k)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return r<EOL><DEDENT>

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 or sequence of int, optional
    Axis along which the percentiles are computed. The default (None)
    is to compute the percentiles along a flattened version of the array.
    A sequence of axes is supported since version 1.9.0.
out : ndarray, optional
    Alternative output array in which to place the result. It must
    have the same shape and buffer length as the expected output,
    but the type (of the output) will be cast if necessary.
overwrite_input : bool, optional
    If True, then allow use of memory of input array `a` for
    calculations. The input array will be modified by the call to
    percentile. This will save memory when you do not need to preserve
    the contents of the input array. In this case you should not make
    any assumptions about the content of the passed in array `a` after
    this function completes -- treat it as undefined. Default is False.
    Note that, if the `a` input is not already an array this parameter
    will have no effect, `a` will be converted to an array internally
    regardless of the value of this parameter.
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
    This optional parameter specifies the interpolation method to use,
    when the desired quantile lies between two data points `i` and `j`:
        * linear: `i + (j - i) * fraction`, where `fraction` is the
          fractional part of the index surrounded by `i` and `j`.
        * lower: `i`.
        * higher: `j`.
        * nearest: `i` or `j` whichever is nearest.
        * midpoint: (`i` + `j`) / 2.

    .. versionadded:: 1.9.0
keepdims : bool, optional
    If this is set to True, the axes which are reduced are left
    in the result as dimensions with size one. With this option,
    the result will broadcast correctly against the original `arr`.

    .. versionadded:: 1.9.0

Returns
-------
percentile : scalar or ndarray
    If a single percentile `q` is given and axis=None a scalar is
    returned.  If multiple percentiles `q` are given an array holding
    the result is returned. The results are listed in the first axis.
    (If `out` is specified, in which case that array is returned
    instead).  If the input contains integers, or floats of smaller
    precision than 64, then the output data-type is float64. Otherwise,
    the output data-type is the same as that of the input.

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)
array([ 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)
array([ 3.5])


wrap = None<EOL>if type(arr) is not ndarray:<EOL><INDENT>try:<EOL><INDENT>wrap = arr.__array_wrap__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>arr = asarray(arr)<EOL>ndim = arr.ndim<EOL>if axis is None:<EOL><INDENT>if ndim != <NUM_LIT:1>:<EOL><INDENT>arr = arr.ravel()<EOL><DEDENT>ndim = arr.ndim<EOL>axis = ndim - <NUM_LIT:1><EOL><DEDENT>if ndim == <NUM_LIT:0>:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning)<EOL>if wrap:<EOL><INDENT>return wrap(arr)<EOL><DEDENT>else:<EOL><INDENT>return arr.copy()<EOL><DEDENT><DEDENT>slobj = [slice(None)]*ndim<EOL>N = arr.shape[axis]<EOL>newshape = list(arr.shape)<EOL>if isinstance(obj, slice):<EOL><INDENT>start, stop, step = obj.indices(N)<EOL>xr = range(start, stop, step)<EOL>numtodel = len(xr)<EOL>if numtodel <= <NUM_LIT:0>:<EOL><INDENT>if wrap:<EOL><INDENT>return wrap(arr.copy())<EOL><DEDENT>else:<EOL><INDENT>return arr.copy()<EOL><DEDENT><DEDENT>if step < <NUM_LIT:0>:<EOL><INDENT>step = -step<EOL>start = xr[-<NUM_LIT:1>]<EOL>stop = xr[<NUM_LIT:0>] + <NUM_LIT:1><EOL><DEDENT>newshape[axis] -= numtodel<EOL>new = empty(newshape, arr.dtype, arr.flags.fnc)<EOL>if start == <NUM_LIT:0>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>slobj[axis] = slice(None, start)<EOL>new[slobj] = arr[slobj]<EOL><DEDENT>if stop == N:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>slobj[axis] = slice(stop-numtodel, None)<EOL>slobj2 = [slice(None)]*ndim<EOL>slobj2[axis] = slice(stop, None)<EOL>new[slobj] = arr[slobj2]<EOL><DEDENT>if step == <NUM_LIT:1>:<EOL><INDENT>pass<EOL><DEDENT>else:  <EOL><INDENT>keep = ones(stop-start, dtype=bool)<EOL>keep[:stop-start:step] = False<EOL>slobj[axis] = slice(start, stop-numtodel)<EOL>slobj2 = [slice(None)]*ndim<EOL>slobj2[axis] = slice(start, stop)<EOL>arr = arr[slobj2]<EOL>slobj2[axis] = keep<EOL>new[slobj] = arr[slobj2]<EOL><DEDENT>if wrap:<EOL><INDENT>return wrap(new)<EOL><DEDENT>else:<EOL><INDENT>return new<EOL><DEDENT><DEDENT>_obj = obj<EOL>obj = np.asarray(obj)<EOL>if obj.dtype == bool:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", FutureWarning)<EOL>obj = obj.astype(intp)<EOL><DEDENT>if isinstance(_obj, (int, long, integer)):<EOL><INDENT>obj = obj.item()<EOL>if (obj < -N or obj >= N):<EOL><INDENT>raise IndexError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (obj, axis, N))<EOL><DEDENT>if (obj < <NUM_LIT:0>):<EOL><INDENT>obj += N<EOL><DEDENT>newshape[axis] -= <NUM_LIT:1><EOL>new = empty(newshape, arr.dtype, arr.flags.fnc)<EOL>slobj[axis] = slice(None, obj)<EOL>new[slobj] = arr[slobj]<EOL>slobj[axis] = slice(obj, None)<EOL>slobj2 = [slice(None)]*ndim<EOL>slobj2[axis] = slice(obj+<NUM_LIT:1>, None)<EOL>new[slobj] = arr[slobj2]<EOL><DEDENT>else:<EOL><INDENT>if obj.size == <NUM_LIT:0> and not isinstance(_obj, np.ndarray):<EOL><INDENT>obj = obj.astype(intp)<EOL><DEDENT>if not np.can_cast(obj, intp, '<STR_LIT>'):<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning)<EOL>obj = obj.astype(intp)<EOL><DEDENT>keep = ones(N, dtype=bool)<EOL>inside_bounds = (obj < N) & (obj >= -N)<EOL>if not inside_bounds.all():<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>DeprecationWarning)<EOL>obj = obj[inside_bounds]<EOL><DEDENT>positive_indices = obj >= <NUM_LIT:0><EOL>if not positive_indices.all():<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", FutureWarning)<EOL>obj = obj[positive_indices]<EOL><DEDENT>keep[obj, ] = False<EOL>slobj[axis] = keep<EOL>new = arr[slobj]<EOL><DEDENT>if wrap:<EOL><INDENT>return wrap(new)<EOL><DEDENT>else:<EOL><INDENT>return new<EOL><DEDENT>

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])


def interp(x, xp, fp, left=None, right=None):

if isinstance(x, (float, int, number)):<EOL><INDENT>return compiled_interp([x], xp, fp, left, right).item()<EOL><DEDENT>elif isinstance(x, np.ndarray) and x.ndim == <NUM_LIT:0>:<EOL><INDENT>return compiled_interp([x], xp, fp, left, right).item()<EOL><DEDENT>else:<EOL><INDENT>return compiled_interp(x, xp, fp, left, right)<EOL><DEDENT>

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]`, default 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')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(xvals, yinterp, '-x')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.show()


def corrcoef(x, y=None, rowvar=<NUM_LIT:1>, bias=<NUM_LIT:0>, ddof=None):

c = cov(x, y, rowvar, bias, ddof)<EOL>try:<EOL><INDENT>d = diag(c)<EOL><DEDENT>except ValueError:  <EOL><INDENT>return c / c<EOL><DEDENT>return c / sqrt(multiply.outer(d, d))<EOL>

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


if len(_nx.shape(ary)) < <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return split(ary, indices_or_sections, <NUM_LIT:2>)<EOL>

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)]


return _nx.concatenate([atleast_3d(_m) for _m in tup], <NUM_LIT:2>)<EOL>

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]]])


def apply_along_axis(func1d, axis, arr, *args, **kwargs):

arr = asarray(arr)<EOL>nd = arr.ndim<EOL>if axis < <NUM_LIT:0>:<EOL><INDENT>axis += nd<EOL><DEDENT>if (axis >= nd):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>% (axis, nd))<EOL><DEDENT>ind = [<NUM_LIT:0>]*(nd-<NUM_LIT:1>)<EOL>i = zeros(nd, '<STR_LIT:O>')<EOL>indlist = list(range(nd))<EOL>indlist.remove(axis)<EOL>i[axis] = slice(None, None)<EOL>outshape = asarray(arr.shape).take(indlist)<EOL>i.put(indlist, ind)<EOL>res = func1d(arr[tuple(i.tolist())], *args, **kwargs)<EOL>if isscalar(res):<EOL><INDENT>outarr = zeros(outshape, asarray(res).dtype)<EOL>outarr[tuple(ind)] = res<EOL>Ntot = product(outshape)<EOL>k = <NUM_LIT:1><EOL>while k < Ntot:<EOL><INDENT>ind[-<NUM_LIT:1>] += <NUM_LIT:1><EOL>n = -<NUM_LIT:1><EOL>while (ind[n] >= outshape[n]) and (n > (<NUM_LIT:1>-nd)):<EOL><INDENT>ind[n-<NUM_LIT:1>] += <NUM_LIT:1><EOL>ind[n] = <NUM_LIT:0><EOL>n -= <NUM_LIT:1><EOL><DEDENT>i.put(indlist, ind)<EOL>res = func1d(arr[tuple(i.tolist())], *args, **kwargs)<EOL>outarr[tuple(ind)] = res<EOL>k += <NUM_LIT:1><EOL><DEDENT>return outarr<EOL><DEDENT>else:<EOL><INDENT>Ntot = product(outshape)<EOL>holdshape = outshape<EOL>outshape = list(arr.shape)<EOL>outshape[axis] = len(res)<EOL>outarr = zeros(outshape, asarray(res).dtype)<EOL>outarr[tuple(i.tolist())] = res<EOL>k = <NUM_LIT:1><EOL>while k < Ntot:<EOL><INDENT>ind[-<NUM_LIT:1>] += <NUM_LIT:1><EOL>n = -<NUM_LIT:1><EOL>while (ind[n] >= holdshape[n]) and (n > (<NUM_LIT:1>-nd)):<EOL><INDENT>ind[n-<NUM_LIT:1>] += <NUM_LIT:1><EOL>ind[n] = <NUM_LIT:0><EOL>n -= <NUM_LIT:1><EOL><DEDENT>i.put(indlist, ind)<EOL>res = func1d(arr[tuple(i.tolist())], *args, **kwargs)<EOL>outarr[tuple(i.tolist())] = res<EOL>k += <NUM_LIT:1><EOL><DEDENT>return outarr<EOL><DEDENT>

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`.
kwargs: any
    Additional named arguments to `func1d`.

    .. versionadded:: 1.9.0

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]])


def _lookfor_generate_cache(module, import_modules, regenerate):

global _lookfor_caches<EOL>import inspect<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>from io import StringIO<EOL><DEDENT>else:<EOL><INDENT>from StringIO import StringIO<EOL><DEDENT>if module is None:<EOL><INDENT>module = "<STR_LIT>"<EOL><DEDENT>if isinstance(module, str):<EOL><INDENT>try:<EOL><INDENT>__import__(module)<EOL><DEDENT>except ImportError:<EOL><INDENT>return {}<EOL><DEDENT>module = sys.modules[module]<EOL><DEDENT>elif isinstance(module, list) or isinstance(module, tuple):<EOL><INDENT>cache = {}<EOL>for mod in module:<EOL><INDENT>cache.update(_lookfor_generate_cache(mod, import_modules,<EOL>regenerate))<EOL><DEDENT>return cache<EOL><DEDENT>if id(module) in _lookfor_caches and not regenerate:<EOL><INDENT>return _lookfor_caches[id(module)]<EOL><DEDENT>cache = {}<EOL>_lookfor_caches[id(module)] = cache<EOL>seen = {}<EOL>index = <NUM_LIT:0><EOL>stack = [(module.__name__, module)]<EOL>while stack:<EOL><INDENT>name, item = stack.pop(<NUM_LIT:0>)<EOL>if id(item) in seen:<EOL><INDENT>continue<EOL><DEDENT>seen[id(item)] = True<EOL>index += <NUM_LIT:1><EOL>kind = "<STR_LIT:object>"<EOL>if inspect.ismodule(item):<EOL><INDENT>kind = "<STR_LIT>"<EOL>try:<EOL><INDENT>_all = item.__all__<EOL><DEDENT>except AttributeError:<EOL><INDENT>_all = None<EOL><DEDENT>if import_modules and hasattr(item, '<STR_LIT>'):<EOL><INDENT>for pth in item.__path__:<EOL><INDENT>for mod_path in os.listdir(pth):<EOL><INDENT>this_py = os.path.join(pth, mod_path)<EOL>init_py = os.path.join(pth, mod_path, '<STR_LIT>')<EOL>if (os.path.isfile(this_py) and<EOL>mod_path.endswith('<STR_LIT>')):<EOL><INDENT>to_import = mod_path[:-<NUM_LIT:3>]<EOL><DEDENT>elif os.path.isfile(init_py):<EOL><INDENT>to_import = mod_path<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT>if to_import == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>base_exc = BaseException<EOL><DEDENT>except NameError:<EOL><INDENT>base_exc = Exception<EOL><DEDENT>try:<EOL><INDENT>old_stdout = sys.stdout<EOL>old_stderr = sys.stderr<EOL>try:<EOL><INDENT>sys.stdout = StringIO()<EOL>sys.stderr = StringIO()<EOL>__import__("<STR_LIT>" % (name, to_import))<EOL><DEDENT>finally:<EOL><INDENT>sys.stdout = old_stdout<EOL>sys.stderr = old_stderr<EOL><DEDENT><DEDENT>except base_exc:<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for n, v in _getmembers(item):<EOL><INDENT>try:<EOL><INDENT>item_name = getattr(v, '<STR_LIT>', "<STR_LIT>" % (name, n))<EOL>mod_name = getattr(v, '<STR_LIT>', None)<EOL><DEDENT>except NameError:<EOL><INDENT>item_name = "<STR_LIT>" % (name, n)<EOL>mod_name = None<EOL><DEDENT>if '<STR_LIT:.>' not in item_name and mod_name:<EOL><INDENT>item_name = "<STR_LIT>" % (mod_name, item_name)<EOL><DEDENT>if not item_name.startswith(name + '<STR_LIT:.>'):<EOL><INDENT>if isinstance(v, ufunc):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>elif not (inspect.ismodule(v) or _all is None or n in _all):<EOL><INDENT>continue<EOL><DEDENT>stack.append(("<STR_LIT>" % (name, n), v))<EOL><DEDENT><DEDENT>elif inspect.isclass(item):<EOL><INDENT>kind = "<STR_LIT:class>"<EOL>for n, v in _getmembers(item):<EOL><INDENT>stack.append(("<STR_LIT>" % (name, n), v))<EOL><DEDENT><DEDENT>elif hasattr(item, "<STR_LIT>"):<EOL><INDENT>kind = "<STR_LIT>"<EOL><DEDENT>try:<EOL><INDENT>doc = inspect.getdoc(item)<EOL><DEDENT>except NameError:<EOL><INDENT>doc = None<EOL><DEDENT>if doc is not None:<EOL><INDENT>cache[name] = (doc, kind, index)<EOL><DEDENT><DEDENT>return cache<EOL>

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.


def ediff1d(ary, to_end=None, to_begin=None):

ary = np.asanyarray(ary).flat<EOL>ed = ary[<NUM_LIT:1>:] - ary[:-<NUM_LIT:1>]<EOL>arrays = [ed]<EOL>if to_begin is not None:<EOL><INDENT>arrays.insert(<NUM_LIT:0>, to_begin)<EOL><DEDENT>if to_end is not None:<EOL><INDENT>arrays.append(to_end)<EOL><DEDENT>if len(arrays) != <NUM_LIT:1>:<EOL><INDENT>ed = np.hstack(arrays)<EOL><DEDENT>return ed<EOL>

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])


def intersect1d(ar1, ar2, assume_unique=False):

if not assume_unique:<EOL><INDENT>ar1 = unique(ar1)<EOL>ar2 = unique(ar2)<EOL><DEDENT>aux = np.concatenate((ar1, ar2))<EOL>aux.sort()<EOL>return aux[:-<NUM_LIT:1>][aux[<NUM_LIT:1>:] == aux[:-<NUM_LIT:1>]]<EOL>

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])


def in1d(ar1, ar2, assume_unique=False, invert=False):

<EOL>ar1 = np.asarray(ar1).ravel()<EOL>ar2 = np.asarray(ar2).ravel()<EOL>if len(ar2) < <NUM_LIT:10> * len(ar1) ** <NUM_LIT>:<EOL><INDENT>if invert:<EOL><INDENT>mask = np.ones(len(ar1), dtype=np.bool)<EOL>for a in ar2:<EOL><INDENT>mask &= (ar1 != a)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>mask = np.zeros(len(ar1), dtype=np.bool)<EOL>for a in ar2:<EOL><INDENT>mask |= (ar1 == a)<EOL><DEDENT><DEDENT>return mask<EOL><DEDENT>if not assume_unique:<EOL><INDENT>ar1, rev_idx = np.unique(ar1, return_inverse=True)<EOL>ar2 = np.unique(ar2)<EOL><DEDENT>ar = np.concatenate((ar1, ar2))<EOL>order = ar.argsort(kind='<STR_LIT>')<EOL>sar = ar[order]<EOL>if invert:<EOL><INDENT>bool_ar = (sar[<NUM_LIT:1>:] != sar[:-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>bool_ar = (sar[<NUM_LIT:1>:] == sar[:-<NUM_LIT:1>])<EOL><DEDENT>flag = np.concatenate((bool_ar, [invert]))<EOL>indx = order.argsort(kind='<STR_LIT>')[:len(ar1)]<EOL>if assume_unique:<EOL><INDENT>return flag[indx]<EOL><DEDENT>else:<EOL><INDENT>return flag[indx][rev_idx]<EOL><DEDENT>

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])


def nanmax(a, axis=None, out=None, keepdims=False):

if not isinstance(a, np.ndarray) or type(a) is np.ndarray:<EOL><INDENT>res = np.fmax.reduce(a, axis=axis, out=out, keepdims=keepdims)<EOL>if np.isnan(res).any():<EOL><INDENT>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>a, mask = _replace_nan(a, -np.inf)<EOL>res = np.amax(a, axis=axis, out=out, keepdims=keepdims)<EOL>if mask is None:<EOL><INDENT>return res<EOL><DEDENT>mask = np.all(mask, axis=axis, keepdims=keepdims)<EOL>if np.any(mask):<EOL><INDENT>res = _copyto(res, np.nan, mask)<EOL>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT><DEDENT>return res<EOL>

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