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


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


own_fh = False<EOL>if not hasattr(file, "<STR_LIT>"):<EOL><INDENT>file = open(file, '<STR_LIT:rb>')<EOL>own_fh = True<EOL><DEDENT>try:<EOL><INDENT>if not hasattr(regexp, '<STR_LIT>'):<EOL><INDENT>regexp = re.compile(asbytes(regexp))<EOL><DEDENT>if not isinstance(dtype, np.dtype):<EOL><INDENT>dtype = np.dtype(dtype)<EOL><DEDENT>seq = regexp.findall(file.read())<EOL>if seq and not isinstance(seq[<NUM_LIT:0>], tuple):<EOL><INDENT>newdtype = np.dtype(dtype[dtype.names[<NUM_LIT:0>]])<EOL>output = np.array(seq, dtype=newdtype)<EOL>output.dtype = dtype<EOL><DEDENT>else:<EOL><INDENT>output = np.array(seq, dtype=dtype)<EOL><DEDENT>return output<EOL><DEDENT>finally:<EOL><INDENT>if own_fh:<EOL><INDENT>file.close()<EOL><DEDENT><DEDENT>

Construct an array from a text file, using regular expression parsing.

The returned array is always a structured array, and is constructed from
all matches of the regular expression in the file. Groups in the regular
expression are converted to fields of the structured array.

Parameters
----------
file : str or file
    File name or file object to read.
regexp : str or regexp
    Regular expression used to parse the file.
    Groups in the regular expression correspond to fields in the dtype.
dtype : dtype or list of dtypes
    Dtype for the structured array.

Returns
-------
output : ndarray
    The output array, containing the part of the content of `file` that
    was matched by `regexp`. `output` is always a structured array.

Raises
------
TypeError
    When `dtype` is not a valid dtype for a structured array.

See Also
--------
fromstring, loadtxt

Notes
-----
Dtypes for structured arrays can be specified in several forms, but all
forms specify at least the data type and field name. For details see
`doc.structured_arrays`.

Examples
--------
>>> f = open('test.dat', 'w')
>>> f.write("1312 foo\\n1534  bar\\n444   qux")
>>> f.close()

>>> regexp = r"(\\d+)\\s+(...)"  # match [digits, whitespace, anything]
>>> output = np.fromregex('test.dat', regexp,
...                       [('num', np.int64), ('key', 'S3')])
>>> output
array([(1312L, 'foo'), (1534L, 'bar'), (444L, 'qux')],
      dtype=[('num', '<i8'), ('key', '|S3')])
>>> output['num']
array([1312, 1534,  444], dtype=int64)


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.


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

Load ASCII data stored in a text file and return a masked array.

Parameters
----------
fname, kwargs : For a description of input parameters, see `genfromtxt`.

See Also
--------
numpy.genfromtxt : generic function to load ASCII data.


kwargs.setdefault("<STR_LIT>", None)<EOL>usemask = kwargs.get('<STR_LIT>', False)<EOL>output = genfromtxt(fname, **kwargs)<EOL>if usemask:<EOL><INDENT>from numpy.ma.mrecords import MaskedRecords<EOL>output = output.view(MaskedRecords)<EOL><DEDENT>else:<EOL><INDENT>output = output.view(np.recarray)<EOL><DEDENT>return output<EOL>

Load ASCII data from a file and return it in a record array.

If ``usemask=False`` a standard `recarray` is returned,
if ``usemask=True`` a MaskedRecords array is returned.

Parameters
----------
fname, kwargs : For a description of input parameters, see `genfromtxt`.

See Also
--------
numpy.genfromtxt : generic function

Notes
-----
By default, `dtype` is None, which means that the data-type of the output
array will be determined from the data.


<EOL>kwargs.setdefault("<STR_LIT>", "<STR_LIT>")<EOL>kwargs.setdefault("<STR_LIT>", True)<EOL>kwargs.setdefault("<STR_LIT>", "<STR_LIT:U+002C>")<EOL>kwargs.setdefault("<STR_LIT>", None)<EOL>output = genfromtxt(fname, **kwargs)<EOL>usemask = kwargs.get("<STR_LIT>", False)<EOL>if usemask:<EOL><INDENT>from numpy.ma.mrecords import MaskedRecords<EOL>output = output.view(MaskedRecords)<EOL><DEDENT>else:<EOL><INDENT>output = output.view(np.recarray)<EOL><DEDENT>return output<EOL>

Load ASCII data stored in a comma-separated file.

The returned array is a record array (if ``usemask=False``, see
`recarray`) or a masked record array (if ``usemask=True``,
see `ma.mrecords.MaskedRecords`).

Parameters
----------
fname, kwargs : For a description of input parameters, see `genfromtxt`.

See Also
--------
numpy.genfromtxt : generic function to load ASCII data.

Notes
-----
By default, `dtype` is None, which means that the data-type of the output
array will be determined from the data.


if self.zip is not None:<EOL><INDENT>self.zip.close()<EOL>self.zip = None<EOL><DEDENT>if self.fid is not None:<EOL><INDENT>self.fid.close()<EOL>self.fid = None<EOL><DEDENT>self.f = None<EOL>


return [(f, self[f]) for f in self.files]<EOL>

Return a list of tuples, with each tuple (filename, array in file).


for f in self.files:<EOL><INDENT>yield (f, self[f])<EOL><DEDENT>

Generator that returns tuples (filename, array in file).


return self.files<EOL>

Return files in the archive with a ``.npy`` extension.


return self.__iter__()<EOL>

Return an iterator over the files in the archive.


<EOL>if not isinstance(index, tuple):<EOL><INDENT>index = (index,)<EOL><DEDENT>fixed = []<EOL>length, dims = len(index), len(self.shape)<EOL>for slice_ in index:<EOL><INDENT>if slice_ is Ellipsis:<EOL><INDENT>fixed.extend([slice(None)] * (dims-length+<NUM_LIT:1>))<EOL>length = len(fixed)<EOL><DEDENT>elif isinstance(slice_, (int, long)):<EOL><INDENT>fixed.append(slice(slice_, slice_+<NUM_LIT:1>, <NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>fixed.append(slice_)<EOL><DEDENT><DEDENT>index = tuple(fixed)<EOL>if len(index) < dims:<EOL><INDENT>index += (slice(None),) * (dims-len(index))<EOL><DEDENT>out = self.__class__(self.var, self.buf_size)<EOL>for i, (start, stop, step, slice_) in enumerate(<EOL>zip(self.start, self.stop, self.step, index)):<EOL><INDENT>out.start[i] = start + (slice_.start or <NUM_LIT:0>)<EOL>out.step[i] = step * (slice_.step or <NUM_LIT:1>)<EOL>out.stop[i] = start + (slice_.stop or stop-start)<EOL>out.stop[i] = min(stop, out.stop[i])<EOL><DEDENT>return out<EOL>


slice_ = tuple(slice(*t) for t in zip(<EOL>self.start, self.stop, self.step))<EOL>return self.var[slice_]<EOL>


for block in self:<EOL><INDENT>for value in block.flat:<EOL><INDENT>yield value<EOL><DEDENT><DEDENT>

A 1-D flat iterator for Arrayterator objects.

This iterator returns elements of the array to be iterated over in
`Arrayterator` one by one. It is similar to `flatiter`.

See Also
--------
`Arrayterator`
flatiter

Examples
--------
>>> a = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6)
>>> a_itor = np.lib.arrayterator.Arrayterator(a, 2)

>>> for subarr in a_itor.flat:
...     if not subarr:
...         print subarr, type(subarr)
...
0 <type 'numpy.int32'>


return tuple(((stop-start-<NUM_LIT:1>)//step+<NUM_LIT:1>) for start, stop, step in<EOL>zip(self.start, self.stop, self.step))<EOL>

The shape of the array to be iterated over.

For an example, see `Arrayterator`.


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 positive infinity, return result as bool array.

Parameters
----------
x : array_like
    The input array.
y : array_like, optional
    A boolean array with the same shape as `x` to store the result.

Returns
-------
y : ndarray
    A boolean array with the same dimensions as the input.
    If second argument is not supplied then a boolean array is returned
    with values True where the corresponding element of the input is
    positive infinity and values False where the element of the input is
    not positive infinity.

    If a second argument is supplied the result is stored there. If the
    type of that array is a numeric type the result is represented as zeros
    and ones, if the type is boolean then as False and True.
    The return value `y` is then a reference to that array.

See Also
--------
isinf, isneginf, isfinite, isnan

Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754).

Errors result if the second argument is also supplied when `x` is a
scalar input, or if first and second arguments have different shapes.

Examples
--------
>>> np.isposinf(np.PINF)
array(True, dtype=bool)
>>> np.isposinf(np.inf)
array(True, dtype=bool)
>>> np.isposinf(np.NINF)
array(False, dtype=bool)
>>> np.isposinf([-np.inf, 0., np.inf])
array([False, False,  True], dtype=bool)

>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([2, 2, 2])
>>> np.isposinf(x, y)
array([0, 0, 1])
>>> y
array([0, 0, 1])


if y is None:<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])


if major < <NUM_LIT:0> or major > <NUM_LIT:255>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if minor < <NUM_LIT:0> or minor > <NUM_LIT:255>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if sys.version_info[<NUM_LIT:0>] < <NUM_LIT:3>:<EOL><INDENT>return MAGIC_PREFIX + chr(major) + chr(minor)<EOL><DEDENT>else:<EOL><INDENT>return MAGIC_PREFIX + bytes([major, minor])<EOL><DEDENT>

Return the magic string for the given file format version.

    Parameters
    ----------
    major : int in [0, 255]
    minor : int in [0, 255]

    Returns
    -------
    magic : str

    Raises
    ------
    ValueError if the version cannot be formatted.


magic_str = _read_bytes(fp, MAGIC_LEN, "<STR_LIT>")<EOL>if magic_str[:-<NUM_LIT:2>] != MAGIC_PREFIX:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-<NUM_LIT:2>]))<EOL><DEDENT>if sys.version_info[<NUM_LIT:0>] < <NUM_LIT:3>:<EOL><INDENT>major, minor = map(ord, magic_str[-<NUM_LIT:2>:])<EOL><DEDENT>else:<EOL><INDENT>major, minor = magic_str[-<NUM_LIT:2>:]<EOL><DEDENT>return major, minor<EOL>

Read the magic string to get the version of the file format.

    Parameters
    ----------
    fp : filelike object

    Returns
    -------
    major : int
    minor : int


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.


d = {}<EOL>d['<STR_LIT>'] = array.shape<EOL>if array.flags.c_contiguous:<EOL><INDENT>d['<STR_LIT>'] = False<EOL><DEDENT>elif array.flags.f_contiguous:<EOL><INDENT>d['<STR_LIT>'] = True<EOL><DEDENT>else:<EOL><INDENT>d['<STR_LIT>'] = False<EOL><DEDENT>d['<STR_LIT>'] = dtype_to_descr(array.dtype)<EOL>return d<EOL>

Get the dictionary of header metadata from a numpy.ndarray.

    Parameters
    ----------
    array : numpy.ndarray

    Returns
    -------
    d : dict
        This has the appropriate entries for writing its string representation
        to the header of the file.


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.


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

Write the header for an array using the 2.0 format.
        The 2.0 format allows storing very large structured arrays.

    .. versionadded:: 1.9.0

    Parameters
    ----------
    fp : filelike object
    d : dict
        This has the appropriate entries for writing its string
        representation to the header of the file.


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


import tokenize<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>tokens = []<EOL>last_token_was_number = False<EOL>for token in tokenize.generate_tokens(StringIO(asstr(s)).read):<EOL><INDENT>token_type = token[<NUM_LIT:0>]<EOL>token_string = token[<NUM_LIT:1>]<EOL>if (last_token_was_number and<EOL>token_type == tokenize.NAME and<EOL>token_string == "<STR_LIT:L>"):<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>tokens.append(token)<EOL><DEDENT>last_token_was_number = (token_type == tokenize.NUMBER)<EOL><DEDENT>return tokenize.untokenize(tokens)<EOL>

Clean up 'L' in npz header ints.

    Cleans up the 'L' in strings representing integers. Needed to allow npz
    headers produced in Python2 to be read in Python3.

    Parameters
    ----------
    s : byte string
        Npy file header.

    Returns
    -------
    header : str
        Cleaned up header.


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


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.


version = read_magic(fp)<EOL>_check_version(version)<EOL>shape, fortran_order, dtype = _read_array_header(fp, version)<EOL>if len(shape) == <NUM_LIT:0>:<EOL><INDENT>count = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>count = numpy.multiply.reduce(shape)<EOL><DEDENT>if dtype.hasobject:<EOL><INDENT>array = pickle.load(fp)<EOL><DEDENT>else:<EOL><INDENT>if isfileobj(fp):<EOL><INDENT>array = numpy.fromfile(fp, dtype=dtype, count=count)<EOL><DEDENT>else:<EOL><INDENT>max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize)<EOL>array = numpy.empty(count, dtype=dtype)<EOL>for i in range(<NUM_LIT:0>, count, max_read_count):<EOL><INDENT>read_count = min(max_read_count, count - i)<EOL>read_size = int(read_count * dtype.itemsize)<EOL>data = _read_bytes(fp, read_size, "<STR_LIT>")<EOL>array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype,<EOL>count=read_count)<EOL><DEDENT><DEDENT>if fortran_order:<EOL><INDENT>array.shape = shape[::-<NUM_LIT:1>]<EOL>array = array.transpose()<EOL><DEDENT>else:<EOL><INDENT>array.shape = shape<EOL><DEDENT><DEDENT>return array<EOL>

Read an array from an NPY file.

Parameters
----------
fp : file_like object
    If this is not a real file object, then this may take extra memory
    and time.

Returns
-------
array : ndarray
    The array from the data on disk.

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


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 _read_bytes(fp, size, error_template="<STR_LIT>"):

data = bytes()<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>r = fp.read(size - len(data))<EOL>data += r<EOL>if len(r) == <NUM_LIT:0> or len(data) == size:<EOL><INDENT>break<EOL><DEDENT><DEDENT>except io.BlockingIOError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if len(data) != size:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise ValueError(msg % (error_template, size, len(data)))<EOL><DEDENT>else:<EOL><INDENT>return data<EOL><DEDENT>

Read from file-like object until size bytes are read.
Raises ValueError if not EOF is encountered before size bytes are read.
Non-blocking objects only supported if they derive from io objects.

Required as e.g. ZipExtFile in python 2.6 can return less data than
requested.


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.


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


m = int(m)<EOL>if m < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if k is None:<EOL><INDENT>k = NX.zeros(m, float)<EOL><DEDENT>k = atleast_1d(k)<EOL>if len(k) == <NUM_LIT:1> and m > <NUM_LIT:1>:<EOL><INDENT>k = k[<NUM_LIT:0>]*NX.ones(m, float)<EOL><DEDENT>if len(k) < m:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>truepoly = isinstance(p, poly1d)<EOL>p = NX.asarray(p)<EOL>if m == <NUM_LIT:0>:<EOL><INDENT>if truepoly:<EOL><INDENT>return poly1d(p)<EOL><DEDENT>return p<EOL><DEDENT>else:<EOL><INDENT>y = NX.concatenate((p.__truediv__(NX.arange(len(p), <NUM_LIT:0>, -<NUM_LIT:1>)), [k[<NUM_LIT:0>]]))<EOL>val = polyint(y, m - <NUM_LIT:1>, k=k[<NUM_LIT:1>:])<EOL>if truepoly:<EOL><INDENT>return poly1d(val)<EOL><DEDENT>return val<EOL><DEDENT>

Return an antiderivative (indefinite integral) of a polynomial.

The returned order `m` antiderivative `P` of polynomial `p` satisfies
:math:`\\frac{d^m}{dx^m}P(x) = p(x)` and is defined up to `m - 1`
integration constants `k`. The constants determine the low-order
polynomial part

.. math:: \\frac{k_{m-1}}{0!} x^0 + \\ldots + \\frac{k_0}{(m-1)!}x^{m-1}

of `P` so that :math:`P^{(j)}(0) = k_{m-j-1}`.

Parameters
----------
p : {array_like, poly1d}
    Polynomial to differentiate.
    A sequence is interpreted as polynomial coefficients, see `poly1d`.
m : int, optional
    Order of the antiderivative. (Default: 1)
k : {None, list of `m` scalars, scalar}, optional
    Integration constants. They are given in the order of integration:
    those corresponding to highest-order terms come first.

    If ``None`` (default), all constants are assumed to be zero.
    If `m = 1`, a single scalar can be given instead of a list.

See Also
--------
polyder : derivative of a polynomial
poly1d.integ : equivalent method

Examples
--------
The defining property of the antiderivative:

>>> p = np.poly1d([1,1,1])
>>> P = np.polyint(p)
>>> P
poly1d([ 0.33333333,  0.5       ,  1.        ,  0.        ])
>>> np.polyder(P) == p
True

The integration constants default to zero, but can be specified:

>>> P = np.polyint(p, 3)
>>> P(0)
0.0
>>> np.polyder(P)(0)
0.0
>>> np.polyder(P, 2)(0)
0.0
>>> P = np.polyint(p, 3, k=[6,5,3])
>>> P
poly1d([ 0.01666667,  0.04166667,  0.16666667,  3. ,  5. ,  3. ])

Note that 3 = 6 / 2!, and that the constants are given in the order of
integrations. Constant of the highest-order polynomial term comes first:

>>> np.polyder(P, 2)(0)
6.0
>>> np.polyder(P, 1)(0)
5.0
>>> P(0)
3.0


m = int(m)<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 polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):

order = int(deg) + <NUM_LIT:1><EOL>x = NX.asarray(x) + <NUM_LIT:0.0><EOL>y = NX.asarray(y) + <NUM_LIT:0.0><EOL>if deg < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if x.ndim != <NUM_LIT:1>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if x.size == <NUM_LIT:0>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if y.ndim < <NUM_LIT:1> or y.ndim > <NUM_LIT:2>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if x.shape[<NUM_LIT:0>] != y.shape[<NUM_LIT:0>]:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if rcond is None:<EOL><INDENT>rcond = len(x)*finfo(x.dtype).eps<EOL><DEDENT>lhs = vander(x, order)<EOL>rhs = y<EOL>if w is not None:<EOL><INDENT>w = NX.asarray(w) + <NUM_LIT:0.0><EOL>if w.ndim != <NUM_LIT:1>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if w.shape[<NUM_LIT:0>] != y.shape[<NUM_LIT:0>]:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>lhs *= w[:, NX.newaxis]<EOL>if rhs.ndim == <NUM_LIT:2>:<EOL><INDENT>rhs *= w[:, NX.newaxis]<EOL><DEDENT>else:<EOL><INDENT>rhs *= w<EOL><DEDENT><DEDENT>scale = NX.sqrt((lhs*lhs).sum(axis=<NUM_LIT:0>))<EOL>lhs /= scale<EOL>c, resids, rank, s = lstsq(lhs, rhs, rcond)<EOL>c = (c.T/scale).T  <EOL>if rank != order and not full:<EOL><INDENT>msg = "<STR_LIT>"<EOL>warnings.warn(msg, RankWarning)<EOL><DEDENT>if full:<EOL><INDENT>return c, resids, rank, s, rcond<EOL><DEDENT>elif cov:<EOL><INDENT>Vbase = inv(dot(lhs.T, lhs))<EOL>Vbase /= NX.outer(scale, scale)<EOL>fac = resids / (len(x) - order - <NUM_LIT>)<EOL>if y.ndim == <NUM_LIT:1>:<EOL><INDENT>return c, Vbase * fac<EOL><DEDENT>else:<EOL><INDENT>return c, Vbase[:,:, NX.newaxis] * fac<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return c<EOL><DEDENT>

Least squares polynomial fit.

Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg`
to points `(x, y)`. Returns a vector of coefficients `p` that minimises
the squared error.

Parameters
----------
x : array_like, shape (M,)
    x-coordinates of the M sample points ``(x[i], y[i])``.
y : array_like, shape (M,) or (M, K)
    y-coordinates of the sample points. Several data sets of sample
    points sharing the same x-coordinates can be fitted at once by
    passing in a 2D-array that contains one dataset per column.
deg : int
    Degree of the fitting polynomial
rcond : float, optional
    Relative condition number of the fit. Singular values smaller than
    this relative to the largest singular value will be ignored. The
    default value is len(x)*eps, where eps is the relative precision of
    the float type, about 2e-16 in most cases.
full : bool, optional
    Switch determining nature of return value. When it is False (the
    default) just the coefficients are returned, when True diagnostic
    information from the singular value decomposition is also returned.
w : array_like, shape (M,), optional
    weights to apply to the y-coordinates of the sample points.
cov : bool, optional
    Return the estimate and the covariance matrix of the estimate
    If full is True, then cov is not returned.

Returns
-------
p : ndarray, shape (M,) or (M, K)
    Polynomial coefficients, highest power first.  If `y` was 2-D, the
    coefficients for `k`-th data set are in ``p[:,k]``.

residuals, rank, singular_values, rcond :
    Present only if `full` = True.  Residuals of the least-squares fit,
    the effective rank of the scaled Vandermonde coefficient matrix,
    its singular values, and the specified value of `rcond`. For more
    details, see `linalg.lstsq`.

V : ndarray, shape (M,M) or (M,M,K)
    Present only if `full` = False and `cov`=True.  The covariance
    matrix of the polynomial coefficient estimates.  The diagonal of
    this matrix are the variance estimates for each coefficient.  If y
    is a 2-D array, then the covariance matrix for the `k`-th data set
    are in ``V[:,:,k]``

Warns
-----
RankWarning
    The rank of the coefficient matrix in the least-squares fit is
    deficient. The warning is only raised if `full` = False.

    The warnings can be turned off by

    >>> import warnings
    >>> warnings.simplefilter('ignore', np.RankWarning)

See Also
--------
polyval : Computes polynomial values.
linalg.lstsq : Computes a least-squares fit.
scipy.interpolate.UnivariateSpline : Computes spline fits.

Notes
-----
The solution minimizes the squared error

.. math ::
    E = \\sum_{j=0}^k |p(x_j) - y_j|^2

in the equations::

    x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0]
    x[1]**n * p[0] + ... + x[1] * p[n-1] + p[n] = y[1]
    ...
    x[k]**n * p[0] + ... + x[k] * p[n-1] + p[n] = y[k]

The coefficient matrix of the coefficients `p` is a Vandermonde matrix.

`polyfit` issues a `RankWarning` when the least-squares fit is badly
conditioned. This implies that the best fit is not well-defined due
to numerical error. The results may be improved by lowering the polynomial
degree or by replacing `x` by `x` - `x`.mean(). The `rcond` parameter
can also be set to a value smaller than its default, but the resulting
fit may be spurious: including contributions from the small singular
values can add numerical noise to the result.

Note that fitting polynomial coefficients is inherently badly conditioned
when the degree of the polynomial is large or the interval of sample points
is badly centered. The quality of the fit should always be checked in these
cases. When polynomial fits are not satisfactory, splines may be a good
alternative.

References
----------
.. [1] Wikipedia, "Curve fitting",
       http://en.wikipedia.org/wiki/Curve_fitting
.. [2] Wikipedia, "Polynomial interpolation",
       http://en.wikipedia.org/wiki/Polynomial_interpolation

Examples
--------
>>> x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
>>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
>>> z = np.polyfit(x, y, 3)
>>> z
array([ 0.08703704, -0.81349206,  1.69312169, -0.03968254])

It is convenient to use `poly1d` objects for dealing with polynomials:

>>> p = np.poly1d(z)
>>> p(0.5)
0.6143849206349179
>>> p(3.5)
-0.34732142857143039
>>> p(10)
22.579365079365115

High-order polynomials may oscillate wildly:

>>> p30 = np.poly1d(np.polyfit(x, y, 30))
/... RankWarning: Polyfit may be poorly conditioned...
>>> p30(4)
-0.80000000000000204
>>> p30(5)
-0.99999999999999445
>>> p30(4.5)
-0.10547061179440398

Illustration:

>>> import matplotlib.pyplot as plt
>>> xp = np.linspace(-2, 6, 100)
>>> _ = plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--')
>>> plt.ylim(-2,2)
(-2, 2)
>>> plt.show()


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


truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))<EOL>a1 = atleast_1d(a1)<EOL>a2 = atleast_1d(a2)<EOL>diff = len(a2) - len(a1)<EOL>if diff == <NUM_LIT:0>:<EOL><INDENT>val = a1 + a2<EOL><DEDENT>elif diff > <NUM_LIT:0>:<EOL><INDENT>zr = NX.zeros(diff, a1.dtype)<EOL>val = NX.concatenate((zr, a1)) + a2<EOL><DEDENT>else:<EOL><INDENT>zr = NX.zeros(abs(diff), a2.dtype)<EOL>val = a1 + NX.concatenate((zr, a2))<EOL><DEDENT>if truepoly:<EOL><INDENT>val = poly1d(val)<EOL><DEDENT>return val<EOL>

Find the sum of two polynomials.

Returns the polynomial resulting from the sum of two input polynomials.
Each input must be either a poly1d object or a 1D sequence of polynomial
coefficients, from highest to lowest degree.

Parameters
----------
a1, a2 : array_like or poly1d object
    Input polynomials.

Returns
-------
out : ndarray or poly1d object
    The sum of the inputs. If either input is a poly1d object, then the
    output is also a poly1d object. Otherwise, it is a 1D array of
    polynomial coefficients from highest to lowest degree.

See Also
--------
poly1d : A one-dimensional polynomial class.
poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval

Examples
--------
>>> np.polyadd([1, 2], [9, 5, 4])
array([9, 6, 6])

Using poly1d objects:

>>> p1 = np.poly1d([1, 2])
>>> p2 = np.poly1d([9, 5, 4])
>>> print p1
1 x + 2
>>> print p2
   2
9 x + 5 x + 4
>>> print np.polyadd(p1, p2)
   2
9 x + 6 x + 6


truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))<EOL>a1 = atleast_1d(a1)<EOL>a2 = atleast_1d(a2)<EOL>diff = len(a2) - len(a1)<EOL>if diff == <NUM_LIT:0>:<EOL><INDENT>val = a1 - a2<EOL><DEDENT>elif diff > <NUM_LIT:0>:<EOL><INDENT>zr = NX.zeros(diff, a1.dtype)<EOL>val = NX.concatenate((zr, a1)) - a2<EOL><DEDENT>else:<EOL><INDENT>zr = NX.zeros(abs(diff), a2.dtype)<EOL>val = a1 - NX.concatenate((zr, a2))<EOL><DEDENT>if truepoly:<EOL><INDENT>val = poly1d(val)<EOL><DEDENT>return val<EOL>

Difference (subtraction) of two polynomials.

Given two polynomials `a1` and `a2`, returns ``a1 - a2``.
`a1` and `a2` can be either array_like sequences of the polynomials'
coefficients (including coefficients equal to zero), or `poly1d` objects.

Parameters
----------
a1, a2 : array_like or poly1d
    Minuend and subtrahend polynomials, respectively.

Returns
-------
out : ndarray or poly1d
    Array or `poly1d` object of the difference polynomial's coefficients.

See Also
--------
polyval, polydiv, polymul, polyadd

Examples
--------
.. math:: (2 x^2 + 10 x - 2) - (3 x^2 + 10 x -4) = (-x^2 + 2)

>>> np.polysub([2, 10, -2], [3, 10, -4])
array([-1,  0,  2])


truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))<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


truepoly = (isinstance(u, poly1d) or isinstance(u, poly1d))<EOL>u = atleast_1d(u) + <NUM_LIT:0.0><EOL>v = atleast_1d(v) + <NUM_LIT:0.0><EOL>w = u[<NUM_LIT:0>] + v[<NUM_LIT:0>]<EOL>m = len(u) - <NUM_LIT:1><EOL>n = len(v) - <NUM_LIT:1><EOL>scale = <NUM_LIT:1.> / v[<NUM_LIT:0>]<EOL>q = NX.zeros((max(m - n + <NUM_LIT:1>, <NUM_LIT:1>),), w.dtype)<EOL>r = u.copy()<EOL>for k in range(<NUM_LIT:0>, m-n+<NUM_LIT:1>):<EOL><INDENT>d = scale * r[k]<EOL>q[k] = d<EOL>r[k:k+n+<NUM_LIT:1>] -= d*v<EOL><DEDENT>while NX.allclose(r[<NUM_LIT:0>], <NUM_LIT:0>, rtol=<NUM_LIT>) and (r.shape[-<NUM_LIT:1>] > <NUM_LIT:1>):<EOL><INDENT>r = r[<NUM_LIT:1>:]<EOL><DEDENT>if truepoly:<EOL><INDENT>return poly1d(q), poly1d(r)<EOL><DEDENT>return q, r<EOL>

Returns the quotient and remainder of polynomial division.

The input arrays are the coefficients (including any coefficients
equal to zero) of the "numerator" (dividend) and "denominator"
(divisor) polynomials, respectively.

Parameters
----------
u : array_like or poly1d
    Dividend polynomial's coefficients.

v : array_like or poly1d
    Divisor polynomial's coefficients.

Returns
-------
q : ndarray
    Coefficients, including those equal to zero, of the quotient.
r : ndarray
    Coefficients, including those equal to zero, of the remainder.

See Also
--------
poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub,
polyval

Notes
-----
Both `u` and `v` must be 0-d or 1-d (ndim = 0 or 1), but `u.ndim` need
not equal `v.ndim`. In other words, all four possible combinations -
``u.ndim = v.ndim = 0``, ``u.ndim = v.ndim = 1``,
``u.ndim = 1, v.ndim = 0``, and ``u.ndim = 0, v.ndim = 1`` - work.

Examples
--------
.. math:: \\frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25

>>> x = np.array([3.0, 5.0, 2.0])
>>> y = np.array([2.0, 1.0])
>>> np.polydiv(x, y)
(array([ 1.5 ,  1.75]), array([ 0.25]))


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


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

Return a derivative of this polynomial.

Refer to `polyder` for full documentation.

See Also
--------
polyder : equivalent function


newdtype = output.dtype<EOL>for field in newdtype.names:<EOL><INDENT>try:<EOL><INDENT>current = input[field]<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT>if current.dtype.names:<EOL><INDENT>recursive_fill_fields(current, output[field])<EOL><DEDENT>else:<EOL><INDENT>output[field][:len(current)] = current<EOL><DEDENT><DEDENT>return output<EOL>

Fills fields from output with fields from input,
with support for nested structures.

Parameters
----------
input : ndarray
    Input array.
output : ndarray
    Output array.

Notes
-----
* `output` should be at least the same size as `input`

Examples
--------
>>> from numpy.lib import recfunctions as rfn
>>> a = np.array([(1, 10.), (2, 20.)], dtype=[('A', int), ('B', float)])
>>> b = np.zeros((3,), dtype=a.dtype)
>>> rfn.recursive_fill_fields(a, b)
array([(1, 10.0), (2, 20.0), (0, 0.0)],
      dtype=[('A', '<i4'), ('B', '<f8')])


listnames = []<EOL>names = adtype.names<EOL>for name in names:<EOL><INDENT>current = adtype[name]<EOL>if current.names:<EOL><INDENT>listnames.append((name, tuple(get_names(current))))<EOL><DEDENT>else:<EOL><INDENT>listnames.append(name)<EOL><DEDENT><DEDENT>return tuple(listnames) or None<EOL>

Returns the field names of the input datatype as a tuple.

Parameters
----------
adtype : dtype
    Input datatype

Examples
--------
>>> from numpy.lib import recfunctions as rfn
>>> rfn.get_names(np.empty((1,), dtype=int)) is None
True
>>> rfn.get_names(np.empty((1,), dtype=[('A',int), ('B', float)]))
('A', 'B')
>>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])])
>>> rfn.get_names(adtype)
('a', ('b', ('ba', 'bb')))


listnames = []<EOL>names = adtype.names<EOL>for name in names:<EOL><INDENT>listnames.append(name)<EOL>current = adtype[name]<EOL>if current.names:<EOL><INDENT>listnames.extend(get_names_flat(current))<EOL><DEDENT><DEDENT>return tuple(listnames) or None<EOL>

Returns the field names of the input datatype as a tuple. Nested structure
are flattend beforehand.

Parameters
----------
adtype : dtype
    Input datatype

Examples
--------
>>> from numpy.lib import recfunctions as rfn
>>> rfn.get_names_flat(np.empty((1,), dtype=int)) is None
True
>>> rfn.get_names_flat(np.empty((1,), dtype=[('A',int), ('B', float)]))
('A', 'B')
>>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])])
>>> rfn.get_names_flat(adtype)
('a', 'b', 'ba', 'bb')


names = ndtype.names<EOL>if names is None:<EOL><INDENT>return ndtype.descr<EOL><DEDENT>else:<EOL><INDENT>descr = []<EOL>for field in names:<EOL><INDENT>(typ, _) = ndtype.fields[field]<EOL>if typ.names:<EOL><INDENT>descr.extend(flatten_descr(typ))<EOL><DEDENT>else:<EOL><INDENT>descr.append((field, typ))<EOL><DEDENT><DEDENT>return tuple(descr)<EOL><DEDENT>

Flatten a structured data-type description.

Examples
--------
>>> from numpy.lib import recfunctions as rfn
>>> ndtype = np.dtype([('a', '<i4'), ('b', [('ba', '<f8'), ('bb', '<i4')])])
>>> rfn.flatten_descr(ndtype)
(('a', dtype('int32')), ('ba', dtype('float64')), ('bb', dtype('int32')))


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 get_fieldstructure(adtype, lastname=None, parents=None,):

if parents is None:<EOL><INDENT>parents = {}<EOL><DEDENT>names = adtype.names<EOL>for name in names:<EOL><INDENT>current = adtype[name]<EOL>if current.names:<EOL><INDENT>if lastname:<EOL><INDENT>parents[name] = [lastname, ]<EOL><DEDENT>else:<EOL><INDENT>parents[name] = []<EOL><DEDENT>parents.update(get_fieldstructure(current, name, parents))<EOL><DEDENT>else:<EOL><INDENT>lastparent = [_ for _ in (parents.get(lastname, []) or [])]<EOL>if lastparent:<EOL><INDENT>lastparent.append(lastname)<EOL><DEDENT>elif lastname:<EOL><INDENT>lastparent = [lastname, ]<EOL><DEDENT>parents[name] = lastparent or []<EOL><DEDENT><DEDENT>return parents or None<EOL>

Returns a dictionary with fields indexing lists of their parent fields.

This function is used to simplify access to fields nested in other fields.

Parameters
----------
adtype : np.dtype
    Input datatype
lastname : optional
    Last processed field name (used internally during recursion).
parents : dictionary
    Dictionary of parent fields (used interbally during recursion).

Examples
--------
>>> from numpy.lib import recfunctions as rfn
>>> ndtype =  np.dtype([('A', int),
...                     ('B', [('BA', int),
...                            ('BB', [('BBA', int), ('BBB', int)])])])
>>> rfn.get_fieldstructure(ndtype)
... # XXX: possible regression, order of BBA and BBB is swapped
{'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'], 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']}


for element in iterable:<EOL><INDENT>if isinstance(element, np.void):<EOL><INDENT>for f in _izip_fields_flat(tuple(element)):<EOL><INDENT>yield f<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield element<EOL><DEDENT><DEDENT>

Returns an iterator of concatenated fields from a sequence of arrays,
collapsing any nested structure.


for element in iterable:<EOL><INDENT>if (hasattr(element, '<STR_LIT>') and<EOL>not isinstance(element, basestring)):<EOL><INDENT>for f in _izip_fields(element):<EOL><INDENT>yield f<EOL><DEDENT><DEDENT>elif isinstance(element, np.void) and len(tuple(element)) == <NUM_LIT:1>:<EOL><INDENT>for f in _izip_fields(element):<EOL><INDENT>yield f<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield element<EOL><DEDENT><DEDENT>

Returns an iterator of concatenated fields from a sequence of arrays.


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 _fix_output(output, usemask=True, asrecarray=False):

if not isinstance(output, MaskedArray):<EOL><INDENT>usemask = False<EOL><DEDENT>if usemask:<EOL><INDENT>if asrecarray:<EOL><INDENT>output = output.view(MaskedRecords)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>output = ma.filled(output)<EOL>if asrecarray:<EOL><INDENT>output = output.view(recarray)<EOL><DEDENT><DEDENT>return output<EOL>

Private function: return a recarray, a ndarray, a MaskedArray
or a MaskedRecords depending on the input parameters


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 merge_arrays(seqarrays, fill_value=-<NUM_LIT:1>, flatten=False,<EOL>usemask=False, asrecarray=False):

<EOL>if (len(seqarrays) == <NUM_LIT:1>):<EOL><INDENT>seqarrays = np.asanyarray(seqarrays[<NUM_LIT:0>])<EOL><DEDENT>if isinstance(seqarrays, (ndarray, np.void)):<EOL><INDENT>seqdtype = seqarrays.dtype<EOL>if (not flatten) or(zip_descr((seqarrays,), flatten=True) == seqdtype.descr):<EOL><INDENT>seqarrays = seqarrays.ravel()<EOL>if not seqdtype.names:<EOL><INDENT>seqdtype = [('<STR_LIT>', seqdtype)]<EOL><DEDENT>if usemask:<EOL><INDENT>if asrecarray:<EOL><INDENT>seqtype = MaskedRecords<EOL><DEDENT>else:<EOL><INDENT>seqtype = MaskedArray<EOL><DEDENT><DEDENT>elif asrecarray:<EOL><INDENT>seqtype = recarray<EOL><DEDENT>else:<EOL><INDENT>seqtype = ndarray<EOL><DEDENT>return seqarrays.view(dtype=seqdtype, type=seqtype)<EOL><DEDENT>else:<EOL><INDENT>seqarrays = (seqarrays,)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>seqarrays = [np.asanyarray(_m) for _m in seqarrays]<EOL><DEDENT>sizes = tuple(a.size for a in seqarrays)<EOL>maxlength = max(sizes)<EOL>newdtype = zip_descr(seqarrays, flatten=flatten)<EOL>seqdata = []<EOL>seqmask = []<EOL>if usemask:<EOL><INDENT>for (a, n) in zip(seqarrays, sizes):<EOL><INDENT>nbmissing = (maxlength - n)<EOL>data = a.ravel().__array__()<EOL>mask = ma.getmaskarray(a).ravel()<EOL>if nbmissing:<EOL><INDENT>fval = _check_fill_value(fill_value, a.dtype)<EOL>if isinstance(fval, (ndarray, np.void)):<EOL><INDENT>if len(fval.dtype) == <NUM_LIT:1>:<EOL><INDENT>fval = fval.item()[<NUM_LIT:0>]<EOL>fmsk = True<EOL><DEDENT>else:<EOL><INDENT>fval = np.array(fval, dtype=a.dtype, ndmin=<NUM_LIT:1>)<EOL>fmsk = np.ones((<NUM_LIT:1>,), dtype=mask.dtype)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>fval = None<EOL>fmsk = True<EOL><DEDENT>seqdata.append(itertools.chain(data, [fval] * nbmissing))<EOL>seqmask.append(itertools.chain(mask, [fmsk] * nbmissing))<EOL><DEDENT>data = tuple(izip_records(seqdata, flatten=flatten))<EOL>output = ma.array(np.fromiter(data, dtype=newdtype, count=maxlength),<EOL>mask=list(izip_records(seqmask, flatten=flatten)))<EOL>if asrecarray:<EOL><INDENT>output = output.view(MaskedRecords)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for (a, n) in zip(seqarrays, sizes):<EOL><INDENT>nbmissing = (maxlength - n)<EOL>data = a.ravel().__array__()<EOL>if nbmissing:<EOL><INDENT>fval = _check_fill_value(fill_value, a.dtype)<EOL>if isinstance(fval, (ndarray, np.void)):<EOL><INDENT>if len(fval.dtype) == <NUM_LIT:1>:<EOL><INDENT>fval = fval.item()[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>fval = np.array(fval, dtype=a.dtype, ndmin=<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>fval = None<EOL><DEDENT>seqdata.append(itertools.chain(data, [fval] * nbmissing))<EOL><DEDENT>output = np.fromiter(tuple(izip_records(seqdata, flatten=flatten)),<EOL>dtype=newdtype, count=maxlength)<EOL>if asrecarray:<EOL><INDENT>output = output.view(recarray)<EOL><DEDENT><DEDENT>return output<EOL>

Merge arrays field by field.

Parameters
----------
seqarrays : sequence of ndarrays
    Sequence of arrays
fill_value : {float}, optional
    Filling value used to pad missing data on the shorter arrays.
flatten : {False, True}, optional
    Whether to collapse nested fields.
usemask : {False, True}, optional
    Whether to return a masked array or not.
asrecarray : {False, True}, optional
    Whether to return a recarray (MaskedRecords) or not.

Examples
--------
>>> from numpy.lib import recfunctions as rfn
>>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.])))
masked_array(data = [(1, 10.0) (2, 20.0) (--, 30.0)],
             mask = [(False, False) (False, False) (True, False)],
       fill_value = (999999, 1e+20),
            dtype = [('f0', '<i4'), ('f1', '<f8')])

>>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.])),
...              usemask=False)
array([(1, 10.0), (2, 20.0), (-1, 30.0)],
      dtype=[('f0', '<i4'), ('f1', '<f8')])
>>> rfn.merge_arrays((np.array([1, 2]).view([('a', int)]),
...               np.array([10., 20., 30.])),
...              usemask=False, asrecarray=True)
rec.array([(1, 10.0), (2, 20.0), (-1, 30.0)],
          dtype=[('a', '<i4'), ('f1', '<f8')])

Notes
-----
* Without a mask, the missing value will be filled with something,
* depending on what its corresponding type:
        -1      for integers
        -1.0    for floating point numbers
        '-'     for characters
        '-1'    for strings
        True    for boolean values
* XXX: I just obtained these values empirically


def drop_fields(base, drop_names, usemask=True, asrecarray=False):

if _is_string_like(drop_names):<EOL><INDENT>drop_names = [drop_names, ]<EOL><DEDENT>else:<EOL><INDENT>drop_names = set(drop_names)<EOL><DEDENT>def _drop_descr(ndtype, drop_names):<EOL><INDENT>names = ndtype.names<EOL>newdtype = []<EOL>for name in names:<EOL><INDENT>current = ndtype[name]<EOL>if name in drop_names:<EOL><INDENT>continue<EOL><DEDENT>if current.names:<EOL><INDENT>descr = _drop_descr(current, drop_names)<EOL>if descr:<EOL><INDENT>newdtype.append((name, descr))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>newdtype.append((name, current))<EOL><DEDENT><DEDENT>return newdtype<EOL><DEDENT>newdtype = _drop_descr(base.dtype, drop_names)<EOL>if not newdtype:<EOL><INDENT>return None<EOL><DEDENT>output = np.empty(base.shape, dtype=newdtype)<EOL>output = recursive_fill_fields(base, output)<EOL>return _fix_output(output, usemask=usemask, asrecarray=asrecarray)<EOL>

Return a new array with fields in `drop_names` dropped.

Nested fields are supported.

Parameters
----------
base : array
    Input array
drop_names : string or sequence
    String or sequence of strings corresponding to the names of the
    fields to drop.
usemask : {False, True}, optional
    Whether to return a masked array or not.
asrecarray : string or sequence, optional
    Whether to return a recarray or a mrecarray (`asrecarray=True`) or
    a plain ndarray or masked array with flexible dtype. The default
    is False.

Examples
--------
>>> from numpy.lib import recfunctions as rfn
>>> a = np.array([(1, (2, 3.0)), (4, (5, 6.0))],
...   dtype=[('a', int), ('b', [('ba', float), ('bb', int)])])
>>> rfn.drop_fields(a, 'a')
array([((2.0, 3),), ((5.0, 6),)],
      dtype=[('b', [('ba', '<f8'), ('bb', '<i4')])])
>>> rfn.drop_fields(a, 'ba')
array([(1, (3,)), (4, (6,))],
      dtype=[('a', '<i4'), ('b', [('bb', '<i4')])])
>>> rfn.drop_fields(a, ['ba', 'bb'])
array([(1,), (4,)],
      dtype=[('a', '<i4')])


return drop_fields(base, drop_names, usemask=False, asrecarray=True)<EOL>

Returns a new numpy.recarray with fields in `drop_names` dropped.


def _recursive_rename_fields(ndtype, namemapper):<EOL><INDENT>newdtype = []<EOL>for name in ndtype.names:<EOL><INDENT>newname = namemapper.get(name, name)<EOL>current = ndtype[name]<EOL>if current.names:<EOL><INDENT>newdtype.append(<EOL>(newname, _recursive_rename_fields(current, namemapper))<EOL>)<EOL><DEDENT>else:<EOL><INDENT>newdtype.append((newname, current))<EOL><DEDENT><DEDENT>return newdtype<EOL><DEDENT>newdtype = _recursive_rename_fields(base.dtype, namemapper)<EOL>return base.view(newdtype)<EOL>

Rename the fields from a flexible-datatype ndarray or recarray.

Nested fields are supported.

Parameters
----------
base : ndarray
    Input array whose fields must be modified.
namemapper : dictionary
    Dictionary mapping old field names to their new version.

Examples
--------
>>> from numpy.lib import recfunctions as rfn
>>> a = np.array([(1, (2, [3.0, 30.])), (4, (5, [6.0, 60.]))],
...   dtype=[('a', int),('b', [('ba', float), ('bb', (float, 2))])])
>>> rfn.rename_fields(a, {'a':'A', 'bb':'BB'})
array([(1, (2.0, [3.0, 30.0])), (4, (5.0, [6.0, 60.0]))],
      dtype=[('A', '<i4'), ('b', [('ba', '<f8'), ('BB', '<f8', 2)])])