def is_valid_linkage(Z, warning=False, throw=False, name=None):

Z = np.asarray(Z, order='<STR_LIT:c>')<EOL>valid = True<EOL>try:<EOL><INDENT>if type(Z) != np.ndarray:<EOL><INDENT>if name:<EOL><INDENT>raise TypeError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT>if Z.dtype != np.double:<EOL><INDENT>if name:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>% name)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT>if len(Z.shape) != <NUM_LIT:2>:<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if Z.shape[<NUM_LIT:1>] != <NUM_LIT:4>:<EOL><INDENT>if name:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>if Z.shape[<NUM_LIT:0>] == <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>n = Z.shape[<NUM_LIT:0>]<EOL>if n > <NUM_LIT:1>:<EOL><INDENT>if ((Z[:, <NUM_LIT:0>] < <NUM_LIT:0>).any() or (Z[:, <NUM_LIT:1>] < <NUM_LIT:0>).any()):<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>if (Z[:, <NUM_LIT:2>] < <NUM_LIT:0>).any():<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>if (Z[:, <NUM_LIT:3>] < <NUM_LIT:0>).any():<EOL><INDENT>if name:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>if _check_hierarchy_uses_cluster_before_formed(Z):<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>if _check_hierarchy_uses_cluster_more_than_once(Z):<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>if throw:<EOL><INDENT>raise<EOL><DEDENT>if warning:<EOL><INDENT>_warning(str(e))<EOL><DEDENT>valid = False<EOL><DEDENT>return valid<EOL>

Checks the validity of a linkage matrix.

A linkage matrix is valid if it is a two dimensional
ndarray (type double) with :math:`n`
rows and 4 columns.  The first two columns must contain indices
between 0 and :math:`2n-1`. For a given row ``i``,
:math:`0 \\leq \\mathtt{Z[i,0]} \\leq i+n-1`
and :math:`0 \\leq Z[i,1] \\leq i+n-1`
(i.e. a cluster cannot join another cluster unless the cluster
being joined has been generated.)

Parameters
----------
Z : array_like
    Linkage matrix.
warning : bool, optional
    When True, issues a Python warning if the linkage
    matrix passed is invalid.
throw : bool, optional
    When True, throws a Python exception if the linkage
    matrix passed is invalid.
name : str, optional
       This string refers to the variable name of the invalid
       linkage matrix.

Returns
-------
b : bool
    True iff the inconsistency matrix is valid.


def _dendrogram_calculate_info(Z, p, truncate_mode,<EOL>color_threshold=np.inf, get_leaves=True,<EOL>orientation='<STR_LIT>', labels=None,<EOL>count_sort=False, distance_sort=False,<EOL>show_leaf_counts=False, i=-<NUM_LIT:1>, iv=<NUM_LIT:0.0>,<EOL>ivl=[], n=<NUM_LIT:0>, icoord_list=[], dcoord_list=[],<EOL>lvs=None, mhr=False,<EOL>current_color=[], color_list=[],<EOL>currently_below_threshold=[],<EOL>leaf_label_func=None, level=<NUM_LIT:0>,<EOL>contraction_marks=None,<EOL>link_color_func=None):

if n == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if i == -<NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if truncate_mode == '<STR_LIT>':<EOL><INDENT>if i < <NUM_LIT:2> * n - p and i >= n:<EOL><INDENT>d = Z[i - n, <NUM_LIT:2>]<EOL>_append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl,<EOL>leaf_label_func, i, labels,<EOL>show_leaf_counts)<EOL>if contraction_marks is not None:<EOL><INDENT>_append_contraction_marks(Z, iv + <NUM_LIT>, i, n, contraction_marks)<EOL><DEDENT>return (iv + <NUM_LIT>, <NUM_LIT>, <NUM_LIT:0.0>, d)<EOL><DEDENT>elif i < n:<EOL><INDENT>_append_singleton_leaf_node(Z, p, n, level, lvs, ivl,<EOL>leaf_label_func, i, labels)<EOL>return (iv + <NUM_LIT>, <NUM_LIT>, <NUM_LIT:0.0>, <NUM_LIT:0.0>)<EOL><DEDENT><DEDENT>elif truncate_mode in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if i > n and level > p:<EOL><INDENT>d = Z[i - n, <NUM_LIT:2>]<EOL>_append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl,<EOL>leaf_label_func, i, labels,<EOL>show_leaf_counts)<EOL>if contraction_marks is not None:<EOL><INDENT>_append_contraction_marks(Z, iv + <NUM_LIT>, i, n, contraction_marks)<EOL><DEDENT>return (iv + <NUM_LIT>, <NUM_LIT>, <NUM_LIT:0.0>, d)<EOL><DEDENT>elif i < n:<EOL><INDENT>_append_singleton_leaf_node(Z, p, n, level, lvs, ivl,<EOL>leaf_label_func, i, labels)<EOL>return (iv + <NUM_LIT>, <NUM_LIT>, <NUM_LIT:0.0>, <NUM_LIT:0.0>)<EOL><DEDENT><DEDENT>elif truncate_mode in ('<STR_LIT>',):<EOL><INDENT>pass<EOL><DEDENT>if i < n:<EOL><INDENT>_append_singleton_leaf_node(Z, p, n, level, lvs, ivl,<EOL>leaf_label_func, i, labels)<EOL>return (iv + <NUM_LIT>, <NUM_LIT>, <NUM_LIT:0.0>, <NUM_LIT:0.0>)<EOL><DEDENT>aa = int(Z[i - n, <NUM_LIT:0>])<EOL>ab = int(Z[i - n, <NUM_LIT:1>])<EOL>if aa > n:<EOL><INDENT>na = Z[aa - n, <NUM_LIT:3>]<EOL>da = Z[aa - n, <NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>na = <NUM_LIT:1><EOL>da = <NUM_LIT:0.0><EOL><DEDENT>if ab > n:<EOL><INDENT>nb = Z[ab - n, <NUM_LIT:3>]<EOL>db = Z[ab - n, <NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>nb = <NUM_LIT:1><EOL>db = <NUM_LIT:0.0><EOL><DEDENT>if count_sort == '<STR_LIT>' or count_sort == True:<EOL><INDENT>if na > nb:<EOL><INDENT>ua = ab<EOL>ub = aa<EOL><DEDENT>else:<EOL><INDENT>ua = aa<EOL>ub = ab<EOL><DEDENT><DEDENT>elif count_sort == '<STR_LIT>':<EOL><INDENT>if na > nb:<EOL><INDENT>ua = aa<EOL>ub = ab<EOL><DEDENT>else:<EOL><INDENT>ua = ab<EOL>ub = aa<EOL><DEDENT><DEDENT>elif distance_sort == '<STR_LIT>' or distance_sort == True:<EOL><INDENT>if da > db:<EOL><INDENT>ua = ab<EOL>ub = aa<EOL><DEDENT>else:<EOL><INDENT>ua = aa<EOL>ub = ab<EOL><DEDENT><DEDENT>elif distance_sort == '<STR_LIT>':<EOL><INDENT>if da > db:<EOL><INDENT>ua = aa<EOL>ub = ab<EOL><DEDENT>else:<EOL><INDENT>ua = ab<EOL>ub = aa<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ua = aa<EOL>ub = ab<EOL><DEDENT>(uiva, uwa, uah, uamd) =_dendrogram_calculate_info(<EOL>Z=Z, p=p,<EOL>truncate_mode=truncate_mode,<EOL>color_threshold=color_threshold,<EOL>get_leaves=get_leaves,<EOL>orientation=orientation,<EOL>labels=labels,<EOL>count_sort=count_sort,<EOL>distance_sort=distance_sort,<EOL>show_leaf_counts=show_leaf_counts,<EOL>i=ua, iv=iv, ivl=ivl, n=n,<EOL>icoord_list=icoord_list,<EOL>dcoord_list=dcoord_list, lvs=lvs,<EOL>current_color=current_color,<EOL>color_list=color_list,<EOL>currently_below_threshold=currently_below_threshold,<EOL>leaf_label_func=leaf_label_func,<EOL>level=level + <NUM_LIT:1>, contraction_marks=contraction_marks,<EOL>link_color_func=link_color_func)<EOL>h = Z[i - n, <NUM_LIT:2>]<EOL>if h >= color_threshold or color_threshold <= <NUM_LIT:0>:<EOL><INDENT>c = '<STR_LIT:b>'<EOL>if currently_below_threshold[<NUM_LIT:0>]:<EOL><INDENT>current_color[<NUM_LIT:0>] = (current_color[<NUM_LIT:0>] + <NUM_LIT:1>) % len(_link_line_colors)<EOL><DEDENT>currently_below_threshold[<NUM_LIT:0>] = False<EOL><DEDENT>else:<EOL><INDENT>currently_below_threshold[<NUM_LIT:0>] = True<EOL>c = _link_line_colors[current_color[<NUM_LIT:0>]]<EOL><DEDENT>(uivb, uwb, ubh, ubmd) =_dendrogram_calculate_info(<EOL>Z=Z, p=p,<EOL>truncate_mode=truncate_mode,<EOL>color_threshold=color_threshold,<EOL>get_leaves=get_leaves,<EOL>orientation=orientation,<EOL>labels=labels,<EOL>count_sort=count_sort,<EOL>distance_sort=distance_sort,<EOL>show_leaf_counts=show_leaf_counts,<EOL>i=ub, iv=iv + uwa, ivl=ivl, n=n,<EOL>icoord_list=icoord_list,<EOL>dcoord_list=dcoord_list, lvs=lvs,<EOL>current_color=current_color,<EOL>color_list=color_list,<EOL>currently_below_threshold=currently_below_threshold,<EOL>leaf_label_func=leaf_label_func,<EOL>level=level + <NUM_LIT:1>, contraction_marks=contraction_marks,<EOL>link_color_func=link_color_func)<EOL>max_dist = max(uamd, ubmd, h)<EOL>icoord_list.append([uiva, uiva, uivb, uivb])<EOL>dcoord_list.append([uah, h, h, ubh])<EOL>if link_color_func is not None:<EOL><INDENT>v = link_color_func(int(i))<EOL>if not isinstance(v, string_types):<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>color_list.append(v)<EOL><DEDENT>else:<EOL><INDENT>color_list.append(c)<EOL><DEDENT>return (((uiva + uivb) / <NUM_LIT:2>), uwa + uwb, h, max_dist)<EOL>

Calculates the endpoints of the links as well as the labels for the
the dendrogram rooted at the node with index i. iv is the independent
variable value to plot the left-most leaf node below the root node i
(if orientation='top', this would be the left-most x value where the
plotting of this root node i and its descendents should begin).

ivl is a list to store the labels of the leaf nodes. The leaf_label_func
is called whenever ivl != None, labels == None, and
leaf_label_func != None. When ivl != None and labels != None, the
labels list is used only for labeling the leaf nodes. When
ivl == None, no labels are generated for leaf nodes.

When get_leaves==True, a list of leaves is built as they are visited
in the dendrogram.

Returns a tuple with l being the independent variable coordinate that
corresponds to the midpoint of cluster to the left of cluster i if
i is non-singleton, otherwise the independent coordinate of the leaf
node if i is a leaf node.

Returns
-------
A tuple (left, w, h, md), where:

  * left is the independent variable coordinate of the center of the
    the U of the subtree

  * w is the amount of space used for the subtree (in independent
    variable units)

  * h is the height of the subtree in dependent variable units

  * md is the max(Z[*,2]) for all nodes * below and including
    the target node.


Z = np.asarray(Z, order='<STR_LIT:c>', dtype=np.double)<EOL>is_valid_linkage(Z, throw=True, name='<STR_LIT>')<EOL>n = Z.shape[<NUM_LIT:0>] + <NUM_LIT:1><EOL>MD = np.zeros((n - <NUM_LIT:1>,))<EOL>[Z] = _copy_arrays_if_base_present([Z])<EOL>_hierarchy.get_max_dist_for_each_cluster(Z, MD, int(n))<EOL>return MD<EOL>

Returns the maximum distance between any non-singleton cluster.

Parameters
----------
Z : ndarray
    The hierarchical clustering encoded as a matrix. See
    ``linkage`` for more information.

Returns
-------
maxdists : ndarray
    A ``(n-1)`` sized numpy array of doubles; ``MD[i]`` represents
    the maximum distance between any cluster (including
    singletons) below and including the node with index i. More
    specifically, ``MD[i] = Z[Q(i)-n, 2].max()`` where ``Q(i)`` is the
    set of all node indices below and including node i.


Z = np.asarray(Z, order='<STR_LIT:c>')<EOL>R = np.asarray(R, order='<STR_LIT:c>')<EOL>is_valid_linkage(Z, throw=True, name='<STR_LIT>')<EOL>is_valid_im(R, throw=True, name='<STR_LIT:R>')<EOL>n = Z.shape[<NUM_LIT:0>] + <NUM_LIT:1><EOL>if Z.shape[<NUM_LIT:0>] != R.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>MI = np.zeros((n - <NUM_LIT:1>,))<EOL>[Z, R] = _copy_arrays_if_base_present([Z, R])<EOL>_hierarchy.get_max_Rfield_for_each_cluster(Z, R, MI, int(n), <NUM_LIT:3>)<EOL>return MI<EOL>

Returns the maximum inconsistency coefficient for each
non-singleton cluster and its descendents.

Parameters
----------
Z : ndarray
    The hierarchical clustering encoded as a matrix. See
    ``linkage`` for more information.
R : ndarray
    The inconsistency matrix.

Returns
-------
MI : ndarray
    A monotonic ``(n-1)``-sized numpy array of doubles.


def pre_order(self, func=(lambda x: x.id)):

<EOL>n = self.count<EOL>curNode = [None] * (<NUM_LIT:2> * n)<EOL>lvisited = set()<EOL>rvisited = set()<EOL>curNode[<NUM_LIT:0>] = self<EOL>k = <NUM_LIT:0><EOL>preorder = []<EOL>while k >= <NUM_LIT:0>:<EOL><INDENT>nd = curNode[k]<EOL>ndid = nd.id<EOL>if nd.is_leaf():<EOL><INDENT>preorder.append(func(nd))<EOL>k = k - <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>if ndid not in lvisited:<EOL><INDENT>curNode[k + <NUM_LIT:1>] = nd.left<EOL>lvisited.add(ndid)<EOL>k = k + <NUM_LIT:1><EOL><DEDENT>elif ndid not in rvisited:<EOL><INDENT>curNode[k + <NUM_LIT:1>] = nd.right<EOL>rvisited.add(ndid)<EOL>k = k + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>k = k - <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return preorder<EOL>

Performs pre-order traversal without recursive function calls.

When a leaf node is first encountered, ``func`` is called with
the leaf node as its argument, and its result is appended to
the list.

For example, the statement::

   ids = root.pre_order(lambda x: x.id)

returns a list of the node ids corresponding to the leaf nodes
of the tree as they appear from left to right.

Parameters
----------
func : function
    Applied to each leaf ClusterNode object in the pre-order traversal.
    Given the i'th leaf node in the pre-ordeR traversal ``n[i]``, the
    result of func(n[i]) is stored in L[i]. If not provided, the index
    of the original observation to which the node corresponds is used.

Returns
-------
L : list
    The pre-order traversal.


return linkage(y, method='<STR_LIT>', metric='<STR_LIT>')<EOL>

Performs weighted/WPGMA linkage on the condensed distance matrix.

See ``linkage`` for more information on the return
structure and algorithm.

Parameters
----------
y : ndarray
    The upper triangular of the distance matrix. The result of
    ``pdist`` is returned in this form.

Returns
-------
Z : ndarray
    A linkage matrix containing the hierarchical clustering. See
    the ``linkage`` function documentation for more information
    on its structure.

See Also
--------
linkage : for advanced creation of hierarchical clusterings.


@classmethod<EOL><INDENT>def from_number(cls, n, min=None):<DEDENT>

width = number_digits(n) + <NUM_LIT:1><EOL>if n < <NUM_LIT:0>:<EOL><INDENT>width += <NUM_LIT:1><EOL><DEDENT>repeat = <NUM_LIT> // width<EOL>return cls(width, min, repeat=repeat)<EOL>

Given an integer, returns a "reasonable" IntFormat instance to represent
        any number between 0 and n if n > 0, -n and n if n < 0

        Parameters
        ----------
        n : int
            max number one wants to be able to represent
        min : int
            minimum number of characters to use for the format

        Returns
        -------
        res : IntFormat
            IntFormat instance with reasonable (see Notes) computed width

        Notes
        -----
        Reasonable should be understood as the minimal string length necessary
        without losing precision. For example, IntFormat.from_number(1) will
        return an IntFormat instance of width 2, so that any 0 and 1 may be
        represented as 1-character strings without loss of information.


@classmethod<EOL><INDENT>def from_data(cls, m, title="<STR_LIT>", key="<STR_LIT:0>", mxtype=None, fmt=None):<DEDENT>

pointer = m.indptr<EOL>indices = m.indices<EOL>values = m.data<EOL>nrows, ncols = m.shape<EOL>nnon_zeros = m.nnz<EOL>if fmt is None:<EOL><INDENT>pointer_fmt = IntFormat.from_number(np.max(pointer+<NUM_LIT:1>))<EOL>indices_fmt = IntFormat.from_number(np.max(indices+<NUM_LIT:1>))<EOL>if values.dtype.kind in np.typecodes["<STR_LIT>"]:<EOL><INDENT>values_fmt = ExpFormat.from_number(-np.max(np.abs(values)))<EOL><DEDENT>elif values.dtype.kind in np.typecodes["<STR_LIT>"]:<EOL><INDENT>values_fmt = IntFormat.from_number(-np.max(np.abs(values)))<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>" % values.dtype.kind)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>if mxtype is None:<EOL><INDENT>if not np.isrealobj(values):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if values.dtype.kind in np.typecodes["<STR_LIT>"]:<EOL><INDENT>tp = "<STR_LIT>"<EOL><DEDENT>elif values.dtype.kind in np.typecodes["<STR_LIT>"]:<EOL><INDENT>tp = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>"<EOL>% values.dtype)<EOL><DEDENT>mxtype = HBMatrixType(tp, "<STR_LIT>", "<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>def _nlines(fmt, size):<EOL><INDENT>nlines = size // fmt.repeat<EOL>if nlines * fmt.repeat != size:<EOL><INDENT>nlines += <NUM_LIT:1><EOL><DEDENT>return nlines<EOL><DEDENT>pointer_nlines = _nlines(pointer_fmt, pointer.size)<EOL>indices_nlines = _nlines(indices_fmt, indices.size)<EOL>values_nlines = _nlines(values_fmt, values.size)<EOL>total_nlines = pointer_nlines + indices_nlines + values_nlines<EOL>return cls(title, key,<EOL>total_nlines, pointer_nlines, indices_nlines, values_nlines,<EOL>mxtype, nrows, ncols, nnon_zeros,<EOL>pointer_fmt.fortran_format, indices_fmt.fortran_format,<EOL>values_fmt.fortran_format)<EOL>

Create a HBInfo instance from an existing sparse matrix.

        Parameters
        ----------
        m : sparse matrix
            the HBInfo instance will derive its parameters from m
        title : str
            Title to put in the HB header
        key : str
            Key
        mxtype : HBMatrixType
            type of the input matrix
        fmt : dict
            not implemented

        Returns
        -------
        hb_info : HBInfo instance


return (fmt.repeat * fmt.width + <NUM_LIT:1>) * (nlines - <NUM_LIT:1>)<EOL>

Return the number of bytes to read to get every full lines for the
    given parsed fortran format.


<EOL>line = fid.readline().strip("<STR_LIT:\n>")<EOL>if not len(line) > <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % line)<EOL><DEDENT>title = line[:<NUM_LIT>]<EOL>key = line[<NUM_LIT>:]<EOL>line = fid.readline().strip("<STR_LIT:\n>")<EOL>if not len(line.rstrip()) >= <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % line)<EOL><DEDENT>total_nlines = _expect_int(line[:<NUM_LIT>])<EOL>pointer_nlines = _expect_int(line[<NUM_LIT>:<NUM_LIT>])<EOL>indices_nlines = _expect_int(line[<NUM_LIT>:<NUM_LIT>])<EOL>values_nlines = _expect_int(line[<NUM_LIT>:<NUM_LIT>])<EOL>rhs_nlines = line[<NUM_LIT>:<NUM_LIT>].strip()<EOL>if rhs_nlines == '<STR_LIT>':<EOL><INDENT>rhs_nlines = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>rhs_nlines = _expect_int(rhs_nlines)<EOL><DEDENT>if not rhs_nlines == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>line = fid.readline().strip("<STR_LIT:\n>")<EOL>if not len(line) >= <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT:%s>" % line)<EOL><DEDENT>mxtype_s = line[:<NUM_LIT:3>].upper()<EOL>if not len(mxtype_s) == <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>mxtype = HBMatrixType.from_fortran(mxtype_s)<EOL>if mxtype.value_type not in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % mxtype)<EOL><DEDENT>if not mxtype.structure == "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % mxtype)<EOL><DEDENT>if not mxtype.storage == "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not line[<NUM_LIT:3>:<NUM_LIT>] == "<STR_LIT:U+0020>" * <NUM_LIT:11>:<EOL><INDENT>raise ValueError("<STR_LIT>" % line)<EOL><DEDENT>nrows = _expect_int(line[<NUM_LIT>:<NUM_LIT>])<EOL>ncols = _expect_int(line[<NUM_LIT>:<NUM_LIT>])<EOL>nnon_zeros = _expect_int(line[<NUM_LIT>:<NUM_LIT>])<EOL>nelementals = _expect_int(line[<NUM_LIT>:<NUM_LIT>])<EOL>if not nelementals == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>% nelementals)<EOL><DEDENT>line = fid.readline().strip("<STR_LIT:\n>")<EOL>ct = line.split()<EOL>if not len(ct) == <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>" % ct)<EOL><DEDENT>return cls(title, key,<EOL>total_nlines, pointer_nlines, indices_nlines, values_nlines,<EOL>mxtype, nrows, ncols, nnon_zeros,<EOL>ct[<NUM_LIT:0>], ct[<NUM_LIT:1>], ct[<NUM_LIT:2>],<EOL>rhs_nlines, nelementals)<EOL>

Create a HBInfo instance from a file object containg a matrix in the
        HB format.

        Parameters
        ----------
        fid : file-like matrix
            File or file-like object containing a matrix in the HB format.

        Returns
        -------
        hb_info : HBInfo instance


self._fid = file<EOL>if hb_info is None:<EOL><INDENT>self._hb_info = HBInfo.from_file(file)<EOL><DEDENT>else:<EOL><INDENT>self._hb_info = hb_info<EOL><DEDENT>

Create a HBFile instance.

        Parameters
        ----------
        file : file-object
            StringIO work as well
        hb_info : HBInfo
            Should be given as an argument for writing, in which case the file
            should be writable.


arr = np.array(*args, **kwargs)<EOL>arr.shape = matdims(arr)<EOL>return arr<EOL>

Convenience function to return matlab-compatible 2D array.


def _check_level(label, expected, actual):

if SP.issparse(expected):  <EOL><INDENT>assert_(SP.issparse(actual))<EOL>assert_array_almost_equal(actual.todense(),<EOL>expected.todense(),<EOL>err_msg=label,<EOL>decimal=<NUM_LIT:5>)<EOL>return<EOL><DEDENT>assert_(types_compatible(expected, actual),<EOL>"<STR_LIT>" %<EOL>(type(expected), type(actual), label))<EOL>if not isinstance(expected,<EOL>(np.void, np.ndarray, MatlabObject)):<EOL><INDENT>assert_equal(expected, actual)<EOL>return<EOL><DEDENT>assert_(expected.shape == actual.shape,<EOL>msg='<STR_LIT>' % (expected.shape,<EOL>actual.shape,<EOL>label))<EOL>ex_dtype = expected.dtype<EOL>if ex_dtype.hasobject:  <EOL><INDENT>if isinstance(expected, MatlabObject):<EOL><INDENT>assert_equal(expected.classname, actual.classname)<EOL><DEDENT>for i, ev in enumerate(expected):<EOL><INDENT>level_label = "<STR_LIT>" % (label, i)<EOL>_check_level(level_label, ev, actual[i])<EOL><DEDENT>return<EOL><DEDENT>if ex_dtype.fields:  <EOL><INDENT>for fn in ex_dtype.fields:<EOL><INDENT>level_label = "<STR_LIT>" % (label, fn)<EOL>_check_level(level_label,<EOL>expected[fn], actual[fn])<EOL><DEDENT>return<EOL><DEDENT>if ex_dtype.type in (text_type,  <EOL>np.unicode_,<EOL>np.bool_):<EOL><INDENT>assert_equal(actual, expected, err_msg=label)<EOL>return<EOL><DEDENT>assert_array_almost_equal(actual, expected, err_msg=label, decimal=<NUM_LIT:5>)<EOL>

Check one level of a potentially nested array


def _make_tag(base_dt, val, mdtype, sde=False):

base_dt = np.dtype(base_dt)<EOL>bo = boc.to_numpy_code(base_dt.byteorder)<EOL>byte_count = base_dt.itemsize<EOL>if not sde:<EOL><INDENT>udt = bo + '<STR_LIT>'<EOL>padding = <NUM_LIT:8> - (byte_count % <NUM_LIT:8>)<EOL>all_dt = [('<STR_LIT>', udt),<EOL>('<STR_LIT>', udt),<EOL>('<STR_LIT>', base_dt)]<EOL>if padding:<EOL><INDENT>all_dt.append(('<STR_LIT>', '<STR_LIT>', padding))<EOL><DEDENT><DEDENT>else:  <EOL><INDENT>udt = bo + '<STR_LIT>'<EOL>padding = <NUM_LIT:4>-byte_count<EOL>if bo == '<STR_LIT:<>':  <EOL><INDENT>all_dt = [('<STR_LIT>', udt),<EOL>('<STR_LIT>', udt),<EOL>('<STR_LIT>', base_dt)]<EOL><DEDENT>else:  <EOL><INDENT>all_dt = [('<STR_LIT>', udt),<EOL>('<STR_LIT>', udt),<EOL>('<STR_LIT>', base_dt)]<EOL><DEDENT>if padding:<EOL><INDENT>all_dt.append(('<STR_LIT>', '<STR_LIT>', padding))<EOL><DEDENT><DEDENT>tag = np.zeros((<NUM_LIT:1>,), dtype=all_dt)<EOL>tag['<STR_LIT>'] = mdtype<EOL>tag['<STR_LIT>'] = byte_count<EOL>tag['<STR_LIT>'] = val<EOL>return tag<EOL>


@docfiller<EOL>def loadmat(file_name, mdict=None, appendmat=True, **kwargs):

variable_names = kwargs.pop('<STR_LIT>', None)<EOL>MR = mat_reader_factory(file_name, appendmat, **kwargs)<EOL>matfile_dict = MR.get_variables(variable_names)<EOL>if mdict is not None:<EOL><INDENT>mdict.update(matfile_dict)<EOL><DEDENT>else:<EOL><INDENT>mdict = matfile_dict<EOL><DEDENT>if isinstance(file_name, string_types):<EOL><INDENT>MR.mat_stream.close()<EOL><DEDENT>return mdict<EOL>

Load MATLAB file

Parameters
----------
file_name : str
   Name of the mat file (do not need .mat extension if
   appendmat==True) Can also pass open file-like object.
m_dict : dict, optional
    Dictionary in which to insert matfile variables.
appendmat : bool, optional
   True to append the .mat extension to the end of the given
   filename, if not already present.
byte_order : str or None, optional
   None by default, implying byte order guessed from mat
   file. Otherwise can be one of ('native', '=', 'little', '<',
   'BIG', '>').
mat_dtype : bool, optional
   If True, return arrays in same dtype as would be loaded into
   MATLAB (instead of the dtype with which they are saved).
squeeze_me : bool, optional
   Whether to squeeze unit matrix dimensions or not.
chars_as_strings : bool, optional
   Whether to convert char arrays to string arrays.
matlab_compatible : bool, optional
   Returns matrices as would be loaded by MATLAB (implies
   squeeze_me=False, chars_as_strings=False, mat_dtype=True,
   struct_as_record=True).
struct_as_record : bool, optional
   Whether to load MATLAB structs as numpy record arrays, or as
   old-style numpy arrays with dtype=object.  Setting this flag to
   False replicates the behavior of scipy version 0.7.x (returning
   numpy object arrays).  The default setting is True, because it
   allows easier round-trip load and save of MATLAB files.
verify_compressed_data_integrity : bool, optional
    Whether the length of compressed sequences in the MATLAB file
    should be checked, to ensure that they are not longer than we expect.
    It is advisable to enable this (the default) because overlong
    compressed sequences in MATLAB files generally indicate that the
    files have experienced some sort of corruption.
variable_names : None or sequence
    If None (the default) - read all variables in file. Otherwise
    `variable_names` should be a sequence of strings, giving names of the
    matlab variables to read from the file.  The reader will skip any
    variable with a name not in this sequence, possibly saving some read
    processing.

Returns
-------
mat_dict : dict
   dictionary with variable names as keys, and loaded matrices as
   values

Notes
-----
v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported.

You will need an HDF5 python library to read matlab 7.3 format mat
files.  Because scipy does not supply one, we do not implement the
HDF5 / 7.3 interface here.


file_is_string = isinstance(file_name, string_types)<EOL>if file_is_string:<EOL><INDENT>if appendmat and file_name[-<NUM_LIT:4>:] != "<STR_LIT>":<EOL><INDENT>file_name = file_name + "<STR_LIT>"<EOL><DEDENT>file_stream = open(file_name, '<STR_LIT:wb>')<EOL><DEDENT>else:<EOL><INDENT>if not hasattr(file_name, '<STR_LIT>'):<EOL><INDENT>raise IOError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>file_stream = file_name<EOL><DEDENT>if format == '<STR_LIT:4>':<EOL><INDENT>if long_field_names:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>MW = MatFile4Writer(file_stream, oned_as)<EOL><DEDENT>elif format == '<STR_LIT:5>':<EOL><INDENT>MW = MatFile5Writer(file_stream,<EOL>do_compression=do_compression,<EOL>unicode_strings=True,<EOL>long_field_names=long_field_names,<EOL>oned_as=oned_as)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>MW.put_variables(mdict)<EOL>if file_is_string:<EOL><INDENT>file_stream.close()<EOL><DEDENT>

Save a dictionary of names and arrays into a MATLAB-style .mat file.

This saves the array objects in the given dictionary to a MATLAB-
style .mat file.

Parameters
----------
file_name : str or file-like object
    Name of the .mat file (.mat extension not needed if ``appendmat ==
    True``).
    Can also pass open file_like object.
mdict : dict
    Dictionary from which to save matfile variables.
appendmat : bool, optional
    True (the default) to append the .mat extension to the end of the
    given filename, if not already present.
format : {'5', '4'}, string, optional
    '5' (the default) for MATLAB 5 and up (to 7.2),
    '4' for MATLAB 4 .mat files
long_field_names : bool, optional
    False (the default) - maximum field name length in a structure is
    31 characters which is the documented maximum length.
    True - maximum field name length in a structure is 63 characters
    which works for MATLAB 7.6+
do_compression : bool, optional
    Whether or not to compress matrices on write.  Default is False.
oned_as : {'row', 'column'}, optional
    If 'column', write 1-D numpy arrays as column vectors.
    If 'row', write 1-D numpy arrays as row vectors.

See also
--------
mio4.MatFile4Writer
mio5.MatFile5Writer


@docfiller<EOL>def mat_reader_factory(file_name, appendmat=True, **kwargs):

byte_stream = _open_file(file_name, appendmat)<EOL>mjv, mnv = get_matfile_version(byte_stream)<EOL>if mjv == <NUM_LIT:0>:<EOL><INDENT>return MatFile4Reader(byte_stream, **kwargs)<EOL><DEDENT>elif mjv == <NUM_LIT:1>:<EOL><INDENT>return MatFile5Reader(byte_stream, **kwargs)<EOL><DEDENT>elif mjv == <NUM_LIT:2>:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % mjv)<EOL><DEDENT>

Create reader for matlab .mat format files

    Parameters
    ----------
    %(file_arg)s
    %(append_arg)s
    %(load_args)s
    %(struct_arg)s

    Returns
    -------
    matreader : MatFileReader object
       Initialized instance of MatFileReader class matching the mat file
       type detected in `filename`.


dims = matdims(arr, oned_as)<EOL>if len(dims) > <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return arr.reshape(dims)<EOL>

Make ``arr`` exactly two dimensional

    If `arr` has more than 2 dimensions, raise a ValueError

    Parameters
    ----------
    arr : array
    oned_as : {'row', 'column'}
       Whether to reshape 1D vectors as row vectors or column vectors.
       See documentation for ``matdims`` for more detail

    Returns
    -------
    arr2d : array
       2D version of the array


if isinstance(variable_names, string_types):<EOL><INDENT>variable_names = [variable_names]<EOL><DEDENT>elif variable_names is not None:<EOL><INDENT>variable_names = list(variable_names)<EOL><DEDENT>self.mat_stream.seek(<NUM_LIT:0>)<EOL>self.initialize_read()<EOL>mdict = {}<EOL>while not self.end_of_stream():<EOL><INDENT>hdr, next_position = self.read_var_header()<EOL>name = asstr(hdr.name)<EOL>if variable_names and name not in variable_names:<EOL><INDENT>self.mat_stream.seek(next_position)<EOL>continue<EOL><DEDENT>mdict[name] = self.read_var_array(hdr)<EOL>self.mat_stream.seek(next_position)<EOL>if variable_names:<EOL><INDENT>variable_names.remove(name)<EOL>if len(variable_names) == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return mdict<EOL>

get variables from stream as dictionary

        Parameters
        ----------
        variable_names : None or str or sequence of str, optional
            variable name, or sequence of variable names to get from Mat file /
            file stream.  If None, then get all variables in file


data = read_dtype(self.mat_stream, self.dtypes['<STR_LIT>'])<EOL>name = self.mat_stream.read(int(data['<STR_LIT>'])).strip(b'<STR_LIT:\x00>')<EOL>if data['<STR_LIT>'] < <NUM_LIT:0> or data['<STR_LIT>'] > <NUM_LIT>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>M, rest = divmod(data['<STR_LIT>'], <NUM_LIT:1000>)  <EOL>if M not in (<NUM_LIT:0>, <NUM_LIT:1>):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>" % order_codes[M],<EOL>UserWarning)<EOL><DEDENT>O, rest = divmod(rest, <NUM_LIT:100>)  <EOL>if O != <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>P, rest = divmod(rest, <NUM_LIT:10>)  <EOL>T = rest  <EOL>dims = (data['<STR_LIT>'], data['<STR_LIT>'])<EOL>is_complex = data['<STR_LIT>'] == <NUM_LIT:1><EOL>dtype = self.dtypes[P]<EOL>return VarHeader4(<EOL>name,<EOL>dtype,<EOL>T,<EOL>dims,<EOL>is_complex)<EOL>


<EOL>if scipy.sparse.issparse(arr):<EOL><INDENT>self.write_sparse(arr, name)<EOL>return<EOL><DEDENT>arr = np.asarray(arr)<EOL>dt = arr.dtype<EOL>if not dt.isnative:<EOL><INDENT>arr = arr.astype(dt.newbyteorder('<STR_LIT:=>'))<EOL><DEDENT>dtt = dt.type<EOL>if dtt is np.object_:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>elif dtt is np.void:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>elif dtt in (np.unicode_, np.string_):<EOL><INDENT>self.write_char(arr, name)<EOL>return<EOL><DEDENT>self.write_numeric(arr, name)<EOL>

Write matrix `arr`, with name `name`

        Parameters
        ----------
        arr : array-like
           array to write
        name : str
           name in matlab workspace


def put_variables(self, mdict, write_header=None):

<EOL>self._matrix_writer = VarWriter4(self)<EOL>for name, var in mdict.items():<EOL><INDENT>self._matrix_writer.write(var, name)<EOL><DEDENT>

Write variables in `mdict` to stream

        Parameters
        ----------
        mdict : mapping
           mapping with method ``items`` return name, contents pairs
           where ``name`` which will appeak in the matlab workspace in
           file load, and ``contents`` is something writeable to a
           matlab file, such as a numpy array.
        write_header : {None, True, False}
           If True, then write the matlab file header before writing the
           variables.  If None (the default) then write the file header
           if we are at position 0 in the stream.  By setting False
           here, and setting the stream position to the end of the file,
           you can append variables to a matlab file


self.mat_stream.seek(<NUM_LIT:0>)<EOL>self.initialize_read()<EOL>vars = []<EOL>while not self.end_of_stream():<EOL><INDENT>hdr, next_position = self.read_var_header()<EOL>name = asstr(hdr.name)<EOL>shape = self._matrix_reader.shape_from_header(hdr)<EOL>info = mclass_info.get(hdr.mclass, '<STR_LIT>')<EOL>vars.append((name, shape, info))<EOL>self.mat_stream.seek(next_position)<EOL><DEDENT>return vars<EOL>


def read_var_array(self, header, process=True):

return self._matrix_reader.array_from_header(header, process)<EOL>

Read array, given `header`

        Parameters
        ----------
        header : header object
           object with fields defining variable header
        process : {True, False}, optional
           If True, apply recursive post-processing during loading of array.

        Returns
        -------
        arr : array
           array with post-processing applied or not according to
           `process`.


mclass = hdr.mclass<EOL>if mclass == mxFULL_CLASS:<EOL><INDENT>shape = tuple(map(int, hdr.dims))<EOL><DEDENT>elif mclass == mxCHAR_CLASS:<EOL><INDENT>shape = tuple(map(int, hdr.dims))<EOL>if self.chars_as_strings:<EOL><INDENT>shape = shape[:-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>elif mclass == mxSPARSE_CLASS:<EOL><INDENT>dt = hdr.dtype<EOL>dims = hdr.dims<EOL>if not (len(dims) == <NUM_LIT:2> and dims[<NUM_LIT:0>] >= <NUM_LIT:1> and dims[<NUM_LIT:1>] >= <NUM_LIT:1>):<EOL><INDENT>return ()<EOL><DEDENT>self.mat_stream.seek(dt.itemsize * (dims[<NUM_LIT:0>] - <NUM_LIT:1>), <NUM_LIT:1>)<EOL>rows = np.ndarray(shape=(<NUM_LIT:1>,), dtype=dt,<EOL>buffer=self.mat_stream.read(dt.itemsize))<EOL>self.mat_stream.seek(dt.itemsize * (dims[<NUM_LIT:0>] - <NUM_LIT:1>), <NUM_LIT:1>)<EOL>cols = np.ndarray(shape=(<NUM_LIT:1>,), dtype=dt,<EOL>buffer=self.mat_stream.read(dt.itemsize))<EOL>shape = (int(rows), int(cols))<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % mclass)<EOL><DEDENT>if self.squeeze_me:<EOL><INDENT>shape = tuple([x for x in shape if x != <NUM_LIT:1>])<EOL><DEDENT>return shape<EOL>

Read the shape of the array described by the header.
        The file position after this call is unspecified.


dtypes = dtype_template.copy()<EOL>for k in dtypes:<EOL><INDENT>dtypes[k] = np.dtype(dtypes[k]).newbyteorder(order_code)<EOL><DEDENT>return dtypes<EOL>

Convert dtypes in mapping to given order

    Parameters
    ----------
    dtype_template : mapping
       mapping with values returning numpy dtype from ``np.dtype(val)``
    order_code : str
       an order code suitable for using in ``dtype.newbyteorder()``

    Returns
    -------
    dtypes : mapping
       mapping where values have been replaced by
       ``np.dtype(val).newbyteorder(order_code)``


return boc.native_code<EOL>

As we do not know what file type we have, assume native


return np.dtype(arr.dtype.str[:<NUM_LIT:2>] + str(num))<EOL>

Return dtype for given number of items per element


<EOL>if write_header is None:<EOL><INDENT>write_header = self.file_stream.tell() == <NUM_LIT:0><EOL><DEDENT>if write_header:<EOL><INDENT>self.write_file_header()<EOL><DEDENT>self._matrix_writer = VarWriter5(self)<EOL>for name, var in mdict.items():<EOL><INDENT>if name[<NUM_LIT:0>] == '<STR_LIT:_>':<EOL><INDENT>continue<EOL><DEDENT>is_global = name in self.global_vars<EOL>if self.do_compression:<EOL><INDENT>stream = BytesIO()<EOL>self._matrix_writer.file_stream = stream<EOL>self._matrix_writer.write_top(var, asbytes(name), is_global)<EOL>out_str = zlib.compress(stream.getvalue())<EOL>tag = np.empty((), NDT_TAG_FULL)<EOL>tag['<STR_LIT>'] = miCOMPRESSED<EOL>tag['<STR_LIT>'] = len(out_str)<EOL>self.file_stream.write(tag.tostring())<EOL>self.file_stream.write(out_str)<EOL><DEDENT>else:  <EOL><INDENT>self._matrix_writer.write_top(var, asbytes(name), is_global)<EOL><DEDENT><DEDENT>

Write variables in `mdict` to stream

        Parameters
        ----------
        mdict : mapping
           mapping with method ``items`` returns name, contents pairs where
           ``name`` which will appear in the matlab workspace in file load, and
           ``contents`` is something writeable to a matlab file, such as a numpy
           array.
        write_header : {None, True, False}
           If True, then write the matlab file header before writing the
           variables.  If None (the default) then write the file header
           if we are at position 0 in the stream.  By setting False
           here, and setting the stream position to the end of the file,
           you can append variables to a matlab file


self.file_stream = file_stream<EOL>self.do_compression = do_compression<EOL>self.unicode_strings = unicode_strings<EOL>if global_vars:<EOL><INDENT>self.global_vars = global_vars<EOL><DEDENT>else:<EOL><INDENT>self.global_vars = []<EOL><DEDENT>self.long_field_names = long_field_names<EOL>self.oned_as = oned_as<EOL>self._matrix_writer = None<EOL>

Initialize writer for matlab 5 format files

        Parameters
        ----------
        %(do_compression)s
        %(unicode_strings)s
        global_vars : None or sequence of strings, optional
            Names of variables to be marked as global for matlab
        %(long_fields)s
        %(oned_as)s


if isinstance(source, np.ndarray):<EOL><INDENT>return source<EOL><DEDENT>if source is None:<EOL><INDENT>return None<EOL><DEDENT>is_mapping = (hasattr(source, '<STR_LIT>') and hasattr(source, '<STR_LIT>') and<EOL>hasattr(source, '<STR_LIT>'))<EOL>if not is_mapping and hasattr(source, '<STR_LIT>'):<EOL><INDENT>source = dict((key, value) for key, value in source.__dict__.items()<EOL>if not key.startswith('<STR_LIT:_>'))<EOL>is_mapping = True<EOL><DEDENT>if is_mapping:<EOL><INDENT>dtype = []<EOL>values = []<EOL>for field, value in source.items():<EOL><INDENT>if (isinstance(field, string_types) and<EOL>field[<NUM_LIT:0>] not in '<STR_LIT>'):<EOL><INDENT>dtype.append((field,object))<EOL>values.append(value)<EOL><DEDENT><DEDENT>if dtype:<EOL><INDENT>return np.array([tuple(values)],dtype)<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>narr = np.asanyarray(source)<EOL>if narr.dtype.type in (np.object, np.object_) andnarr.shape == () and narr == source:<EOL><INDENT>return None<EOL><DEDENT>return narr<EOL>

Convert input object ``source`` to something we can write

    Parameters
    ----------
    source : object

    Returns
    -------
    arr : ndarray

    Examples
    --------
    >>> to_writeable(np.array([1])) # pass through ndarrays
    array([1])
    >>> expected = np.array([(1, 2)], dtype=[('a', '|O8'), ('b', '|O8')])
    >>> np.all(to_writeable({'a':1,'b':2}) == expected)
    True
    >>> np.all(to_writeable({'a':1,'b':2, '_c':3}) == expected)
    True
    >>> np.all(to_writeable({'a':1,'b':2, 100:3}) == expected)
    True
    >>> np.all(to_writeable({'a':1,'b':2, '99':3}) == expected)
    True
    >>> class klass(object): pass
    >>> c = klass
    >>> c.a = 1
    >>> c.b = 2
    >>> np.all(to_writeable({'a':1,'b':2}) == expected)
    True
    >>> to_writeable([])
    array([], dtype=float64)
    >>> to_writeable(())
    array([], dtype=float64)
    >>> to_writeable(None)

    >>> to_writeable('a string').dtype.type == np.str_
    True
    >>> to_writeable(1)
    array(1)
    >>> to_writeable([1])
    array([1])
    >>> to_writeable([1])
    array([1])
    >>> to_writeable(object()) # not convertable

    dict keys with legal characters are convertible

    >>> to_writeable({'a':1})['a']
    array([1], dtype=object)

    but not with illegal characters

    >>> to_writeable({'1':1}) is None
    True
    >>> to_writeable({'_a':1}) is None
    True


A = arr.tocsc()  <EOL>A.sort_indices()     <EOL>is_complex = (A.dtype.kind == '<STR_LIT:c>')<EOL>is_logical = (A.dtype.kind == '<STR_LIT:b>')<EOL>nz = A.nnz<EOL>self.write_header(matdims(arr, self.oned_as),<EOL>mxSPARSE_CLASS,<EOL>is_complex=is_complex,<EOL>is_logical=is_logical,<EOL>nzmax=nz)<EOL>self.write_element(A.indices.astype('<STR_LIT>'))<EOL>self.write_element(A.indptr.astype('<STR_LIT>'))<EOL>self.write_element(A.data.real)<EOL>if is_complex:<EOL><INDENT>self.write_element(A.data.imag)<EOL><DEDENT>


<EOL>name = self._var_name<EOL>is_global = self._var_is_global<EOL>self._mat_tag_pos = self.file_stream.tell()<EOL>self.write_bytes(self.mat_tag)<EOL>af = np.zeros((), NDT_ARRAY_FLAGS)<EOL>af['<STR_LIT>'] = miUINT32<EOL>af['<STR_LIT>'] = <NUM_LIT:8><EOL>flags = is_complex << <NUM_LIT:3> | is_global << <NUM_LIT:2> | is_logical << <NUM_LIT:1><EOL>af['<STR_LIT>'] = mclass | flags << <NUM_LIT:8><EOL>af['<STR_LIT>'] = nzmax<EOL>self.write_bytes(af)<EOL>self.write_element(np.array(shape, dtype='<STR_LIT>'))<EOL>name = np.asarray(name)<EOL>if name == '<STR_LIT>':  <EOL><INDENT>self.write_smalldata_element(name, miINT8, <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>self.write_element(name, miINT8)<EOL><DEDENT>self._var_name = '<STR_LIT>'<EOL>self._var_is_global = False<EOL>

Write header for given data options
        shape : sequence
           array shape
        mclass      - mat5 matrix class
        is_complex  - True if matrix is complex
        is_logical  - True if matrix is logical
        nzmax        - max non zero elements for sparse arrays

        We get the name and the global flag from the object, and reset
        them to defaults after we've used them


assert_equal(ncfileobj.history, b'<STR_LIT>')<EOL>time = ncfileobj.variables['<STR_LIT:time>']<EOL>assert_equal(time.units, b'<STR_LIT>')<EOL>assert_equal(time.shape, (N_EG_ELS,))<EOL>assert_equal(time[-<NUM_LIT:1>], N_EG_ELS-<NUM_LIT:1>)<EOL>


assert_equal(a, b)<EOL>if type(b) is np.str:<EOL><INDENT>assert_equal(type(a), type(b))<EOL><DEDENT>else:<EOL><INDENT>assert_equal(np.asarray(a).dtype.type, np.asarray(b).dtype.type)<EOL><DEDENT>

Assert whether value AND type are the same


if hasattr(filename,'<STR_LIT>'):<EOL><INDENT>fid = filename<EOL><DEDENT>else:<EOL><INDENT>fid = open(filename, '<STR_LIT:wb>')<EOL><DEDENT>try:<EOL><INDENT>dkind = data.dtype.kind<EOL>if not (dkind == '<STR_LIT:i>' or dkind == '<STR_LIT:f>' or (dkind == '<STR_LIT:u>' and data.dtype.itemsize == <NUM_LIT:1>)):<EOL><INDENT>raise ValueError("<STR_LIT>" % data.dtype)<EOL><DEDENT>fid.write(b'<STR_LIT>')<EOL>fid.write(b'<STR_LIT>')<EOL>fid.write(b'<STR_LIT>')<EOL>fid.write(b'<STR_LIT>')<EOL>if dkind == '<STR_LIT:f>':<EOL><INDENT>comp = <NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>comp = <NUM_LIT:1><EOL><DEDENT>if data.ndim == <NUM_LIT:1>:<EOL><INDENT>noc = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>noc = data.shape[<NUM_LIT:1>]<EOL><DEDENT>bits = data.dtype.itemsize * <NUM_LIT:8><EOL>sbytes = rate*(bits // <NUM_LIT:8>)*noc<EOL>ba = noc * (bits // <NUM_LIT:8>)<EOL>fid.write(struct.pack('<STR_LIT>', <NUM_LIT:16>, comp, noc, rate, sbytes, ba, bits))<EOL>fid.write(b'<STR_LIT:data>')<EOL>fid.write(struct.pack('<STR_LIT>', data.nbytes))<EOL>if data.dtype.byteorder == '<STR_LIT:>>' or (data.dtype.byteorder == '<STR_LIT:=>' and sys.byteorder == '<STR_LIT>'):<EOL><INDENT>data = data.byteswap()<EOL><DEDENT>_array_tofile(fid, data)<EOL>size = fid.tell()<EOL>fid.seek(<NUM_LIT:4>)<EOL>fid.write(struct.pack('<STR_LIT>', size-<NUM_LIT:8>))<EOL><DEDENT>finally:<EOL><INDENT>if not hasattr(filename,'<STR_LIT>'):<EOL><INDENT>fid.close()<EOL><DEDENT>else:<EOL><INDENT>fid.seek(<NUM_LIT:0>)<EOL><DEDENT><DEDENT>

Write a numpy array as a WAV file

Parameters
----------
filename : string or open file handle
    Output wav file
rate : int
    The sample rate (in samples/sec).
data : ndarray
    A 1-D or 2-D numpy array of either integer or float data-type.

Notes
-----
* The file can be an open file or a filename.

* Writes a simple uncompressed WAV file.
* The bits-per-sample will be determined by the data-type.
* To write multiple-channels, use a 2-D array of shape
  (Nsamples, Nchannels).


if dtype is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>dtype = np.dtype(dtype)<EOL>firstSize = self._read_size()<EOL>if firstSize % dtype.itemsize != <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(firstSize, dtype.itemsize))<EOL><DEDENT>data = np.fromfile(self._fp, dtype=dtype, count=firstSize//dtype.itemsize)<EOL>secondSize = self._read_size()<EOL>if firstSize != secondSize:<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT>return data<EOL>

Reads a record of a given type from the file.

Parameters
----------
dtype : data-type
    Data type specifying the size and endiness of the data.

Returns
-------
data : ndarray
    A one-dimensional array object.

Notes
-----
If the record contains a multi-dimensional array, calling reshape or
resize will restructure the array to the correct size.
Since Fortran multidimensional arrays are stored in column-major format,
this may have some non-intuitive consequences. If the variable was
declared as 'INTEGER var(5,4)', for example, var could be read with
'read_record(dtype=np.integer).reshape( (4,5) )' since Python uses
row-major ordering of indices.

One can transpose to obtain the indices in the same order as in Fortran.

For records that contain several variables or mixed types (as opposed
to single scalar or array types), it is possible to specify a dtype
with mixed types:

>>> record = f.read_record([('a', '<f4'), ('b', '<i4')])
>>> record['a']  # access the variable 'a'
5.6

and if any of the variables are arrays, the shape can be specified as
the third item in the relevant tuple:

>>> record = f.read_record([('a', '<f4'), ('b', '<i4', (3,3))])

Numpy also supports a short syntax for this kind of type:

>>> record = f.read_record('<f4,(3,3)<i4')
>>> record['f0']  # variables are called f0, f1, ...
5.6

See Also
--------
read_reals
read_ints


return MMFile().read(source)<EOL>

Reads the contents of a Matrix Market file 'filename' into a matrix.

Parameters
----------

source : file
    Matrix Market filename (extensions .mtx, .mtz.gz)
    or open file object.

Returns
-------
a:
    Sparse or full matrix


close_it = False<EOL>if isinstance(filespec, string_types):<EOL><INDENT>close_it = True<EOL>if mode[<NUM_LIT:0>] == '<STR_LIT:r>':<EOL><INDENT>if not os.path.isfile(filespec):<EOL><INDENT>if os.path.isfile(filespec+'<STR_LIT>'):<EOL><INDENT>filespec = filespec + '<STR_LIT>'<EOL><DEDENT>elif os.path.isfile(filespec+'<STR_LIT>'):<EOL><INDENT>filespec = filespec + '<STR_LIT>'<EOL><DEDENT>elif os.path.isfile(filespec+'<STR_LIT>'):<EOL><INDENT>filespec = filespec + '<STR_LIT>'<EOL><DEDENT><DEDENT>if filespec.endswith('<STR_LIT>'):<EOL><INDENT>import gzip<EOL>stream = gzip.open(filespec, mode)<EOL><DEDENT>elif filespec.endswith('<STR_LIT>'):<EOL><INDENT>import bz2<EOL>stream = bz2.BZ2File(filespec, '<STR_LIT:rb>')<EOL><DEDENT>else:<EOL><INDENT>stream = open(filespec, mode)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if filespec[-<NUM_LIT:4>:] != '<STR_LIT>':<EOL><INDENT>filespec = filespec + '<STR_LIT>'<EOL><DEDENT>stream = open(filespec, mode)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>stream = filespec<EOL><DEDENT>return stream, close_it<EOL>

Return an open file stream for reading based on source.  If source is
a file name, open it (after trying to find it with mtx and gzipped mtx
extensions).  Otherwise, just return source.


def mmwrite(target, a, comment='<STR_LIT>', field=None, precision=None):

MMFile().write(target, a, comment, field, precision)<EOL>

Writes the sparse or dense array `a` to a Matrix Market formatted file.

Parameters
----------
target : file
    Matrix Market filename (extension .mtx) or open file object
a : array like
    Sparse or dense 2D array
comment : str, optional
    comments to be prepended to the Matrix Market file
field : None or str, optional
    Either 'real', 'complex', 'pattern', or 'integer'.
precision : None or int, optional
    Number of digits to display for real or complex values.


i = next(ofile)<EOL>while r_comment.match(i):<EOL><INDENT>i = next(ofile)<EOL><DEDENT>relation = None<EOL>attributes = []<EOL>while not r_datameta.match(i):<EOL><INDENT>m = r_headerline.match(i)<EOL>if m:<EOL><INDENT>isattr = r_attribute.match(i)<EOL>if isattr:<EOL><INDENT>name, type, i = tokenize_attribute(ofile, i)<EOL>attributes.append((name, type))<EOL><DEDENT>else:<EOL><INDENT>isrel = r_relation.match(i)<EOL>if isrel:<EOL><INDENT>relation = isrel.group(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % i)<EOL><DEDENT>i = next(ofile)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>i = next(ofile)<EOL><DEDENT><DEDENT>return relation, attributes<EOL>


return itertools.dropwhile(lambda x: not r_datameta.match(x), ofile)<EOL>

Skip header.

    the first next() call of the returned iterator will be the @data line


r_nominal = re.compile('<STR_LIT>')<EOL>m = r_nominal.match(atrv)<EOL>if m:<EOL><INDENT>return tuple(i.strip() for i in m.group(<NUM_LIT:1>).split('<STR_LIT:U+002C>'))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Given a string containing a nominal type, returns a tuple of the
    possible values.

    A nominal type is defined as something framed between braces ({}).

    Parameters
    ----------
    atrv : str
       Nominal type definition

    Returns
    -------
    poss_vals : tuple
       possible values

    Examples
    --------
    >>> get_nom_val("{floup, bouga, fl, ratata}")
    ('floup', 'bouga', 'fl', 'ratata')


if not self.fp.closed:<EOL><INDENT>try:<EOL><INDENT>self.flush()<EOL><DEDENT>finally:<EOL><INDENT>self.variables = {}<EOL>if self._mm_buf is not None:<EOL><INDENT>ref = weakref.ref(self._mm_buf)<EOL>self._mm_buf = None<EOL>if ref() is None:<EOL><INDENT>self._mm.close()<EOL><DEDENT>else:<EOL><INDENT>warnings.warn((<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>), category=RuntimeWarning)<EOL><DEDENT><DEDENT>self._mm = None<EOL>self.fp.close()<EOL><DEDENT><DEDENT>


def createVariable(self, name, type, dimensions):

shape = tuple([self.dimensions[dim] for dim in dimensions])<EOL>shape_ = tuple([dim or <NUM_LIT:0> for dim in shape])  <EOL>type = dtype(type)<EOL>typecode, size = type.char, type.itemsize<EOL>if (typecode, size) not in REVERSE:<EOL><INDENT>raise ValueError("<STR_LIT>" % type)<EOL><DEDENT>data = empty(shape_, dtype=type.newbyteorder("<STR_LIT:B>"))  <EOL>self.variables[name] = netcdf_variable(data, typecode, size, shape, dimensions)<EOL>return self.variables[name]<EOL>

Create an empty variable for the `netcdf_file` object, specifying its data
type and the dimensions it uses.

Parameters
----------
name : str
    Name of the new variable.
type : dtype or str
    Data type of the variable.
dimensions : sequence of str
    List of the dimension names used by the variable, in the desired order.

Returns
-------
variable : netcdf_variable
    The newly created ``netcdf_variable`` object.
    This object has also been added to the `netcdf_file` object as well.

See Also
--------
createDimension

Notes
-----
Any dimensions to be used by the variable should already exist in the
NetCDF data structure or should be created by `createDimension` prior to
creating the NetCDF variable.


return self._typecode<EOL>

Return the typecode of the variable.

Returns
-------
typecode : char
    The character typecode of the variable (eg, 'i' for int).


if not self.data.flags.writeable:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>self.data.itemset(value)<EOL>

Assign a scalar value to a `netcdf_variable` of length one.

Parameters
----------
value : scalar
    Scalar value (of compatible type) to assign to a length-one netcdf
    variable. This value will be written to file.

Raises
------
ValueError
    If the input is not a scalar, or if the destination is not a length-one
    netcdf variable.


structdesc = {}<EOL>structstart = _read_long(f)<EOL>if structstart != <NUM_LIT:9>:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>structdesc['<STR_LIT:name>'] = _read_string(f)<EOL>predef = _read_long(f)<EOL>structdesc['<STR_LIT>'] = _read_long(f)<EOL>structdesc['<STR_LIT>'] = _read_long(f)<EOL>structdesc['<STR_LIT>'] = predef & <NUM_LIT:1><EOL>structdesc['<STR_LIT>'] = predef & <NUM_LIT:2><EOL>structdesc['<STR_LIT>'] = predef & <NUM_LIT:4><EOL>if not structdesc['<STR_LIT>']:<EOL><INDENT>structdesc['<STR_LIT>'] = []<EOL>for t in range(structdesc['<STR_LIT>']):<EOL><INDENT>structdesc['<STR_LIT>'].append(_read_tagdesc(f))<EOL><DEDENT>for tag in structdesc['<STR_LIT>']:<EOL><INDENT>tag['<STR_LIT:name>'] = _read_string(f)<EOL><DEDENT>structdesc['<STR_LIT>'] = {}<EOL>for tag in structdesc['<STR_LIT>']:<EOL><INDENT>if tag['<STR_LIT>']:<EOL><INDENT>structdesc['<STR_LIT>'][tag['<STR_LIT:name>']] = _read_arraydesc(f)<EOL><DEDENT><DEDENT>structdesc['<STR_LIT>'] = {}<EOL>for tag in structdesc['<STR_LIT>']:<EOL><INDENT>if tag['<STR_LIT>']:<EOL><INDENT>structdesc['<STR_LIT>'][tag['<STR_LIT:name>']] = _read_structdesc(f)<EOL><DEDENT><DEDENT>if structdesc['<STR_LIT>'] or structdesc['<STR_LIT>']:<EOL><INDENT>structdesc['<STR_LIT>'] = _read_string(f)<EOL>structdesc['<STR_LIT>'] = _read_long(f)<EOL>structdesc['<STR_LIT>'] = []<EOL>for s in range(structdesc['<STR_LIT>']):<EOL><INDENT>structdesc['<STR_LIT>'].append(_read_string(f))<EOL><DEDENT>structdesc['<STR_LIT>'] = []<EOL>for s in range(structdesc['<STR_LIT>']):<EOL><INDENT>structdesc['<STR_LIT>'].append(_read_structdesc(f))<EOL><DEDENT><DEDENT>STRUCT_DICT[structdesc['<STR_LIT:name>']] = structdesc<EOL><DEDENT>else:<EOL><INDENT>if not structdesc['<STR_LIT:name>'] in STRUCT_DICT:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>structdesc = STRUCT_DICT[structdesc['<STR_LIT:name>']]<EOL><DEDENT>return structdesc<EOL>

Function to read in a structure descriptor


def _read_array(f, typecode, array_desc):

if typecode in [<NUM_LIT:1>, <NUM_LIT:3>, <NUM_LIT:4>, <NUM_LIT:5>, <NUM_LIT:6>, <NUM_LIT:9>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:15>]:<EOL><INDENT>if typecode == <NUM_LIT:1>:<EOL><INDENT>nbytes = _read_int32(f)<EOL>if nbytes != array_desc['<STR_LIT>']:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT><DEDENT>array = np.fromstring(f.read(array_desc['<STR_LIT>']),<EOL>dtype=DTYPE_DICT[typecode])<EOL><DEDENT>elif typecode in [<NUM_LIT:2>, <NUM_LIT:12>]:<EOL><INDENT>array = np.fromstring(f.read(array_desc['<STR_LIT>']*<NUM_LIT:2>),<EOL>dtype=DTYPE_DICT[typecode])[<NUM_LIT:1>::<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>array = []<EOL>for i in range(array_desc['<STR_LIT>']):<EOL><INDENT>dtype = typecode<EOL>data = _read_data(f, dtype)<EOL>array.append(data)<EOL><DEDENT>array = np.array(array, dtype=np.object_)<EOL><DEDENT>if array_desc['<STR_LIT>'] > <NUM_LIT:1>:<EOL><INDENT>dims = array_desc['<STR_LIT>'][:int(array_desc['<STR_LIT>'])]<EOL>dims.reverse()<EOL>array = array.reshape(dims)<EOL><DEDENT>_align_32(f)<EOL>return array<EOL>

Read an array of type `typecode`, with the array descriptor given as
`array_desc`.


return np.int32(struct.unpack('<STR_LIT>', f.read(<NUM_LIT:4>))[<NUM_LIT:0>])<EOL>


length = _read_long(f)<EOL>if length > <NUM_LIT:0>:<EOL><INDENT>chars = _read_bytes(f, length)<EOL>_align_32(f)<EOL>chars = asstr(chars)<EOL><DEDENT>else:<EOL><INDENT>chars = '<STR_LIT>'<EOL><DEDENT>return chars<EOL>


return np.uint16(struct.unpack('<STR_LIT>', f.read(<NUM_LIT:4>)[<NUM_LIT:2>:<NUM_LIT:4>])[<NUM_LIT:0>])<EOL>


return np.uint8(struct.unpack('<STR_LIT>', f.read(<NUM_LIT:4>)[:<NUM_LIT:1>])[<NUM_LIT:0>])<EOL>


return np.float32(struct.unpack('<STR_LIT>', f.read(<NUM_LIT:4>))[<NUM_LIT:0>])<EOL>


typedesc = {}<EOL>typedesc['<STR_LIT>'] = _read_long(f)<EOL>typedesc['<STR_LIT>'] = _read_long(f)<EOL>if typedesc['<STR_LIT>'] & <NUM_LIT:2> == <NUM_LIT:2>:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>typedesc['<STR_LIT>'] = typedesc['<STR_LIT>'] & <NUM_LIT:4> == <NUM_LIT:4><EOL>typedesc['<STR_LIT>'] = typedesc['<STR_LIT>'] & <NUM_LIT:32> == <NUM_LIT:32><EOL>if typedesc['<STR_LIT>']:<EOL><INDENT>typedesc['<STR_LIT>'] = _read_arraydesc(f)<EOL>typedesc['<STR_LIT>'] = _read_structdesc(f)<EOL><DEDENT>elif typedesc['<STR_LIT>']:<EOL><INDENT>typedesc['<STR_LIT>'] = _read_arraydesc(f)<EOL><DEDENT>return typedesc<EOL>


arraydesc = {}<EOL>arraydesc['<STR_LIT>'] = _read_long(f)<EOL>if arraydesc['<STR_LIT>'] == <NUM_LIT:8>:<EOL><INDENT>_skip_bytes(f, <NUM_LIT:4>)<EOL>arraydesc['<STR_LIT>'] = _read_long(f)<EOL>arraydesc['<STR_LIT>'] = _read_long(f)<EOL>arraydesc['<STR_LIT>'] = _read_long(f)<EOL>_skip_bytes(f, <NUM_LIT:8>)<EOL>arraydesc['<STR_LIT>'] = _read_long(f)<EOL>arraydesc['<STR_LIT>'] = []<EOL>for d in range(arraydesc['<STR_LIT>']):<EOL><INDENT>arraydesc['<STR_LIT>'].append(_read_long(f))<EOL><DEDENT><DEDENT>elif arraydesc['<STR_LIT>'] == <NUM_LIT>:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL>_skip_bytes(f, <NUM_LIT:8>)<EOL>arraydesc['<STR_LIT>'] = _read_uint64(f)<EOL>arraydesc['<STR_LIT>'] = _read_uint64(f)<EOL>arraydesc['<STR_LIT>'] = _read_long(f)<EOL>_skip_bytes(f, <NUM_LIT:8>)<EOL>arraydesc['<STR_LIT>'] = <NUM_LIT:8><EOL>arraydesc['<STR_LIT>'] = []<EOL>for d in range(arraydesc['<STR_LIT>']):<EOL><INDENT>v = _read_long(f)<EOL>if v != <NUM_LIT:0>:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>arraydesc['<STR_LIT>'].append(_read_long(f))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % arraydesc['<STR_LIT>'])<EOL><DEDENT>return arraydesc<EOL>


if Np < ndiv + <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if Np % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>from scipy import linalg<EOL>ho = Np >> <NUM_LIT:1><EOL>x = arange(-ho,ho+<NUM_LIT:1.0>)<EOL>x = x[:,newaxis]<EOL>X = x**<NUM_LIT:0.0><EOL>for k in range(<NUM_LIT:1>,Np):<EOL><INDENT>X = hstack([X,x**k])<EOL><DEDENT>w = product(arange(<NUM_LIT:1>,ndiv+<NUM_LIT:1>),axis=<NUM_LIT:0>)*linalg.inv(X)[ndiv]<EOL>return w<EOL>

Return weights for an Np-point central derivative.

Assumes equally-spaced function points.

If weights are in the vector w, then
derivative is w[0] * f(x-ho*dx) + ... + w[-1] * f(x+h0*dx)

Parameters
----------
Np : int
    Number of points for the central derivative.
ndiv : int, optional
    Number of divisions.  Default is 1.

Notes
-----
Can be inaccurate for large number of points.


import pickle<EOL>import os<EOL>fname = os.path.join(os.path.dirname(__file__),'<STR_LIT>')<EOL>with open(fname, '<STR_LIT:rb>') as f:<EOL><INDENT>ascent = array(pickle.load(f))<EOL><DEDENT>return ascent<EOL>

Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy use in demos

The image is derived from accent-to-the-top.jpg at
http://www.public-domain-image.com/people-public-domain-images-pictures/

Parameters
----------
None

Returns
-------
ascent : ndarray
   convenient image to use for testing and demonstration

Examples
--------
>>> import scipy.misc
>>> ascent = scipy.misc.ascent()
>>> ascent.shape
(512, 512)
>>> ascent.max()
255

>>> import matplotlib.pyplot as plt
>>> plt.gray()
>>> plt.imshow(ascent)
>>> plt.show()


import bz2<EOL>import os<EOL>with open(os.path.join(os.path.dirname(__file__), '<STR_LIT>'), '<STR_LIT:rb>') as f:<EOL><INDENT>rawdata = f.read()<EOL><DEDENT>data = bz2.decompress(rawdata)<EOL>face = fromstring(data, dtype='<STR_LIT>')<EOL>face.shape = (<NUM_LIT>, <NUM_LIT>, <NUM_LIT:3>)<EOL>if gray is True:<EOL><INDENT>face = (<NUM_LIT> * face[:,:,<NUM_LIT:0>] + <NUM_LIT> * face[:,:,<NUM_LIT:1>] + <NUM_LIT> * face[:,:,<NUM_LIT:2>]).astype('<STR_LIT>')<EOL><DEDENT>return face<EOL>

Get a 1024 x 768, color image of a raccoon face.

raccoon-procyon-lotor.jpg at http://www.public-domain-image.com

Parameters
----------
gray : bool, optional
    If True then return color image, otherwise return an 8-bit gray-scale

Returns
-------
face : ndarray
    image of a racoon face

Examples
--------
>>> import scipy.misc
>>> face = scipy.misc.face()
>>> face.shape
(768, 1024, 3)
>>> face.max()
230
>>> face.dtype
dtype('uint8')

>>> import matplotlib.pyplot as plt
>>> plt.gray()
>>> plt.imshow(face)
>>> plt.show()


if not docstring:<EOL><INDENT>return docstring<EOL><DEDENT>if docdict is None:<EOL><INDENT>docdict = {}<EOL><DEDENT>if not docdict:<EOL><INDENT>return docstring<EOL><DEDENT>lines = docstring.expandtabs().splitlines()<EOL>if len(lines) < <NUM_LIT:2>:<EOL><INDENT>icount = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>icount = indentcount_lines(lines[<NUM_LIT:1>:])<EOL><DEDENT>indent = '<STR_LIT:U+0020>' * icount<EOL>indented = {}<EOL>for name, dstr in docdict.items():<EOL><INDENT>lines = dstr.expandtabs().splitlines()<EOL>try:<EOL><INDENT>newlines = [lines[<NUM_LIT:0>]]<EOL>for line in lines[<NUM_LIT:1>:]:<EOL><INDENT>newlines.append(indent+line)<EOL><DEDENT>indented[name] = '<STR_LIT:\n>'.join(newlines)<EOL><DEDENT>except IndexError:<EOL><INDENT>indented[name] = dstr<EOL><DEDENT><DEDENT>return docstring % indented<EOL>

Fill a function docstring from variables in dictionary

    Adapt the indent of the inserted docs

    Parameters
    ----------
    docstring : string
        docstring from function, possibly with dict formatting strings
    docdict : dict
        dictionary with keys that match the dict formatting strings
        and values that are docstring fragments to be inserted.  The
        indentation of the inserted docstrings is set to match the
        minimum indentation of the ``docstring`` by adding this
        indentation to all lines of the inserted string, except the
        first

    Returns
    -------
    outstring : string
        string with requested ``docdict`` strings inserted

    Examples
    --------
    >>> docformat(' Test string with %(value)s', {'value':'inserted value'})
    ' Test string with inserted value'
    >>> docstring = 'First line\\n    Second line\\n    %(value)s'
    >>> inserted_string = "indented\\nstring"
    >>> docdict = {'value': inserted_string}
    >>> docformat(docstring, docdict)
    'First line\\n    Second line\\n    indented\\n    string'


def _doc(func):<EOL><INDENT>cls_docstring = getattr(cls, func.__name__).__doc__<EOL>func_docstring = func.__doc__<EOL>if func_docstring is None:<EOL><INDENT>func.__doc__ = cls_docstring<EOL><DEDENT>else:<EOL><INDENT>new_docstring = func_docstring % dict(super=cls_docstring)<EOL>func.__doc__ = new_docstring<EOL><DEDENT>return func<EOL><DEDENT>return _doc<EOL>

This decorator modifies the decorated function's docstring by
replacing occurrences of '%(super)s' with the docstring of the
method of the same name from the class `cls`.

If the decorated method has no docstring, it is simply given the
docstring of `cls`s method.

Parameters
----------
cls : Python class or instance
    A class with a method with the same name as the decorated method.
    The docstring of the method in this class replaces '%(super)s' in the
    docstring of the decorated method.

Returns
-------
f : function
    The decorator function that modifies the __doc__ attribute
    of its argument.

Examples
--------
In the following, the docstring for Bar.func created using the
docstring of `Foo.func`.

>>> class Foo(object):
...     def func(self):
...         '''Do something useful.'''
...         return
...
>>> class Bar(Foo):
...     @inherit_docstring_from(Foo)
...     def func(self):
...         '''%(super)s
...         Do it fast.
...         '''
...         return
...
>>> b = Bar()
>>> b.func.__doc__
'Do something useful.\n        Do it fast.\n        '


def fmin_l_bfgs_b(func, x0, fprime=None, args=(),<EOL>approx_grad=<NUM_LIT:0>,<EOL>bounds=None, m=<NUM_LIT:10>, factr=<NUM_LIT>, pgtol=<NUM_LIT>,<EOL>epsilon=<NUM_LIT>,<EOL>iprint=-<NUM_LIT:1>, maxfun=<NUM_LIT>, maxiter=<NUM_LIT>, disp=None,<EOL>callback=None):

<EOL>if approx_grad:<EOL><INDENT>fun = func<EOL>jac = None<EOL><DEDENT>elif fprime is None:<EOL><INDENT>fun = MemoizeJac(func)<EOL>jac = fun.derivative<EOL><DEDENT>else:<EOL><INDENT>fun = func<EOL>jac = fprime<EOL><DEDENT>if disp is None:<EOL><INDENT>disp = iprint<EOL><DEDENT>opts = {'<STR_LIT>': disp,<EOL>'<STR_LIT>': iprint,<EOL>'<STR_LIT>': m,<EOL>'<STR_LIT>': factr * np.finfo(float).eps,<EOL>'<STR_LIT>': pgtol,<EOL>'<STR_LIT>': epsilon,<EOL>'<STR_LIT>': maxfun,<EOL>'<STR_LIT>': maxiter,<EOL>'<STR_LIT>': callback}<EOL>res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds,<EOL>**opts)<EOL>d = {'<STR_LIT>': res['<STR_LIT>'],<EOL>'<STR_LIT>': res['<STR_LIT:message>'],<EOL>'<STR_LIT>': res['<STR_LIT>'],<EOL>'<STR_LIT>': res['<STR_LIT>'],<EOL>'<STR_LIT>': res['<STR_LIT:status>']}<EOL>f = res['<STR_LIT>']<EOL>x = res['<STR_LIT:x>']<EOL>return x, f, d<EOL>

Minimize a function func using the L-BFGS-B algorithm.

Parameters
----------
func : callable f(x,*args)
    Function to minimise.
x0 : ndarray
    Initial guess.
fprime : callable fprime(x,*args)
    The gradient of `func`.  If None, then `func` returns the function
    value and the gradient (``f, g = func(x, *args)``), unless
    `approx_grad` is True in which case `func` returns only ``f``.
args : sequence
    Arguments to pass to `func` and `fprime`.
approx_grad : bool
    Whether to approximate the gradient numerically (in which case
    `func` returns only the function value).
bounds : list
    ``(min, max)`` pairs for each element in ``x``, defining
    the bounds on that parameter. Use None for one of ``min`` or
    ``max`` when there is no bound in that direction.
m : int
    The maximum number of variable metric corrections
    used to define the limited memory matrix. (The limited memory BFGS
    method does not store the full hessian but uses this many terms in an
    approximation to it.)
factr : float
    The iteration stops when
    ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``,
    where ``eps`` is the machine precision, which is automatically
    generated by the code. Typical values for `factr` are: 1e12 for
    low accuracy; 1e7 for moderate accuracy; 10.0 for extremely
    high accuracy.
pgtol : float
    The iteration will stop when
    ``max{|proj g_i | i = 1, ..., n} <= pgtol``
    where ``pg_i`` is the i-th component of the projected gradient.
epsilon : float
    Step size used when `approx_grad` is True, for numerically
    calculating the gradient
iprint : int
    Controls the frequency of output. ``iprint < 0`` means no output;
    ``iprint == 0`` means write messages to stdout; ``iprint > 1`` in
    addition means write logging information to a file named
    ``iterate.dat`` in the current working directory.
disp : int, optional
    If zero, then no output.  If a positive number, then this over-rides
    `iprint` (i.e., `iprint` gets the value of `disp`).
maxfun : int
    Maximum number of function evaluations.
maxiter : int
    Maximum number of iterations.
callback : callable, optional
    Called after each iteration, as ``callback(xk)``, where ``xk`` is the
    current parameter vector.

Returns
-------
x : array_like
    Estimated position of the minimum.
f : float
    Value of `func` at the minimum.
d : dict
    Information dictionary.

    * d['warnflag'] is

      - 0 if converged,
      - 1 if too many function evaluations or too many iterations,
      - 2 if stopped for another reason, given in d['task']

    * d['grad'] is the gradient at the minimum (should be 0 ish)
    * d['funcalls'] is the number of function calls made.
    * d['nit'] is the number of iterations.

See also
--------
minimize: Interface to minimization algorithms for multivariate
    functions. See the 'L-BFGS-B' `method` in particular.

Notes
-----
License of L-BFGS-B (FORTRAN code):

The version included here (in fortran code) is 3.0
(released April 25, 2011).  It was written by Ciyou Zhu, Richard Byrd,
and Jorge Nocedal <nocedal@ece.nwu.edu>. It carries the following
condition for use:

This software is freely available, but we expect that all publications
describing work using this software, or all commercial products using it,
quote at least one of the references given below. This software is released
under the BSD License.

References
----------
* R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound
  Constrained Optimization, (1995), SIAM Journal on Scientific and
  Statistical Computing, 16, 5, pp. 1190-1208.
* C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,
  FORTRAN routines for large scale bound constrained optimization (1997),
  ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560.
* J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B,
  FORTRAN routines for large scale bound constrained optimization (2011),
  ACM Transactions on Mathematical Software, 38, 1.


def fprime_ieqcon(self, x, sign=<NUM_LIT:1.0>):

return np.array([[<NUM_LIT:1>, -<NUM_LIT:1>]])<EOL>


def f_eqcon(self, x, sign=<NUM_LIT:1.0>):

return np.array([x[<NUM_LIT:0>] - x[<NUM_LIT:1>]])<EOL>


return np.asarray(x)<EOL>


def fprime_eqcon(self, x, sign=<NUM_LIT:1.0>):


def f_eqcon_scalar(self, x, sign=<NUM_LIT:1.0>):

return self.f_eqcon(x, sign)[<NUM_LIT:0>]<EOL>


np.random.seed(<NUM_LIT:0>)<EOL>c = - np.random.exponential(size=(m,n))<EOL>Arow = np.zeros((m,m*n))<EOL>brow = np.zeros(m)<EOL>for j in range(m):<EOL><INDENT>j1 = j + <NUM_LIT:1><EOL>Arow[j,j*n:j1*n] = <NUM_LIT:1><EOL>brow[j] = n/m<EOL><DEDENT>Acol = np.zeros((n,m*n))<EOL>bcol = np.zeros(n)<EOL>for j in range(n):<EOL><INDENT>j1 = j + <NUM_LIT:1><EOL>Acol[j,j::n] = <NUM_LIT:1><EOL>bcol[j] = <NUM_LIT:1><EOL><DEDENT>A = np.vstack((Arow,Acol))<EOL>b = np.hstack((brow,bcol))<EOL>return A, b, c.ravel()<EOL>

-> A b c LP test: m*n vars, m+n constraints
        row sums == n/m, col sums == 1
        https://gist.github.com/denis-bz/8647461


def get_boundaries_intersections(self, z, d, trust_radius):

a = np.dot(d, d)<EOL>b = <NUM_LIT:2> * np.dot(z, d)<EOL>c = np.dot(z, z) - trust_radius**<NUM_LIT:2><EOL>sqrt_discriminant = math.sqrt(b*b - <NUM_LIT:4>*a*c)<EOL>ta = (-b - sqrt_discriminant) / (<NUM_LIT:2>*a)<EOL>tb = (-b + sqrt_discriminant) / (<NUM_LIT:2>*a)<EOL>return ta, tb<EOL>

Solve the scalar quadratic equation ||z + t d|| == trust_radius.
This is like a line-sphere intersection.
Return the two values of t, sorted from low to high.


if self._g_mag is None:<EOL><INDENT>self._g_mag = scipy.linalg.norm(self.jac)<EOL><DEDENT>return self._g_mag<EOL>

Magniture of jacobian of objective function at current iteration.


if self._f is None:<EOL><INDENT>self._f = self._fun(self._x)<EOL><DEDENT>return self._f<EOL>

Value of objective function at current iteration.


if self.collapsed is not None:<EOL><INDENT>return np.dot(self.collapsed, v)<EOL><DEDENT>return LowRankMatrix._matvec(v, self.alpha, self.cs, self.ds)<EOL>


def nonlin_solve(F, x0, jacobian='<STR_LIT>', iter=None, verbose=False,<EOL>maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,<EOL>tol_norm=None, line_search='<STR_LIT>', callback=None,<EOL>full_output=False, raise_exception=True):

condition = TerminationCondition(f_tol=f_tol, f_rtol=f_rtol,<EOL>x_tol=x_tol, x_rtol=x_rtol,<EOL>iter=iter, norm=tol_norm)<EOL>x0 = _as_inexact(x0)<EOL>func = lambda z: _as_inexact(F(_array_like(z, x0))).flatten()<EOL>x = x0.flatten()<EOL>dx = np.inf<EOL>Fx = func(x)<EOL>Fx_norm = norm(Fx)<EOL>jacobian = asjacobian(jacobian)<EOL>jacobian.setup(x.copy(), Fx, func)<EOL>if maxiter is None:<EOL><INDENT>if iter is not None:<EOL><INDENT>maxiter = iter + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>maxiter = <NUM_LIT:100>*(x.size+<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line_search is True:<EOL><INDENT>line_search = '<STR_LIT>'<EOL><DEDENT>elif line_search is False:<EOL><INDENT>line_search = None<EOL><DEDENT>if line_search not in (None, '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>gamma = <NUM_LIT><EOL>eta_max = <NUM_LIT><EOL>eta_treshold = <NUM_LIT:0.1><EOL>eta = <NUM_LIT><EOL>for n in xrange(maxiter):<EOL><INDENT>status = condition.check(Fx, x, dx)<EOL>if status:<EOL><INDENT>break<EOL><DEDENT>tol = min(eta, eta*Fx_norm)<EOL>dx = -jacobian.solve(Fx, tol=tol)<EOL>if norm(dx) == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if line_search:<EOL><INDENT>s, x, Fx, Fx_norm_new = _nonlin_line_search(func, x, Fx, dx,<EOL>line_search)<EOL><DEDENT>else:<EOL><INDENT>s = <NUM_LIT:1.0><EOL>x = x + dx<EOL>Fx = func(x)<EOL>Fx_norm_new = norm(Fx)<EOL><DEDENT>jacobian.update(x.copy(), Fx)<EOL>if callback:<EOL><INDENT>callback(x, Fx)<EOL><DEDENT>eta_A = gamma * Fx_norm_new**<NUM_LIT:2> / Fx_norm**<NUM_LIT:2><EOL>if gamma * eta**<NUM_LIT:2> < eta_treshold:<EOL><INDENT>eta = min(eta_max, eta_A)<EOL><DEDENT>else:<EOL><INDENT>eta = min(eta_max, max(eta_A, gamma*eta**<NUM_LIT:2>))<EOL><DEDENT>Fx_norm = Fx_norm_new<EOL>if verbose:<EOL><INDENT>sys.stdout.write("<STR_LIT>" % (<EOL>n, norm(Fx), s, eta))<EOL>sys.stdout.flush()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if raise_exception:<EOL><INDENT>raise NoConvergence(_array_like(x, x0))<EOL><DEDENT>else:<EOL><INDENT>status = <NUM_LIT:2><EOL><DEDENT><DEDENT>if full_output:<EOL><INDENT>info = {'<STR_LIT>': condition.iteration,<EOL>'<STR_LIT>': Fx,<EOL>'<STR_LIT:status>': status,<EOL>'<STR_LIT:success>': status == <NUM_LIT:1>,<EOL>'<STR_LIT:message>': {<NUM_LIT:1>: '<STR_LIT>'<EOL>'<STR_LIT>',<EOL><NUM_LIT:2>: '<STR_LIT>'<EOL>'<STR_LIT>'<EOL>}[status]<EOL>}<EOL>return _array_like(x, x0), info<EOL><DEDENT>else:<EOL><INDENT>return _array_like(x, x0)<EOL><DEDENT>

Find a root of a function, in a way suitable for large-scale problems.

Parameters
----------
%(params_basic)s
jacobian : Jacobian
    A Jacobian approximation: `Jacobian` object or something that
    `asjacobian` can transform to one. Alternatively, a string specifying
    which of the builtin Jacobian approximations to use:

        krylov, broyden1, broyden2, anderson
        diagbroyden, linearmixing, excitingmixing

%(params_extra)s
full_output : bool
    If true, returns a dictionary `info` containing convergence
    information.
raise_exception : bool
    If True, a `NoConvergence` exception is raise if no solution is found.

See Also
--------
asjacobian, Jacobian

Notes
-----
This algorithm implements the inexact Newton method, with
backtracking or full line searches. Several Jacobian
approximations are available, including Krylov and Quasi-Newton
methods.

References
----------
.. [KIM] C. T. Kelley, \"Iterative Methods for Linear and Nonlinear
   Equations\". Society for Industrial and Applied Mathematics. (1995)
   http://www.siam.org/books/kelley/


@staticmethod<EOL><INDENT>def _solve(v, alpha, cs, ds):<DEDENT>

if len(cs) == <NUM_LIT:0>:<EOL><INDENT>return v/alpha<EOL><DEDENT>axpy, dotc = get_blas_funcs(['<STR_LIT>', '<STR_LIT>'], cs[:<NUM_LIT:1>] + [v])<EOL>c0 = cs[<NUM_LIT:0>]<EOL>A = alpha * np.identity(len(cs), dtype=c0.dtype)<EOL>for i, d in enumerate(ds):<EOL><INDENT>for j, c in enumerate(cs):<EOL><INDENT>A[i,j] += dotc(d, c)<EOL><DEDENT><DEDENT>q = np.zeros(len(cs), dtype=c0.dtype)<EOL>for j, d in enumerate(ds):<EOL><INDENT>q[j] = dotc(d, v)<EOL><DEDENT>q /= alpha<EOL>q = solve(A, q)<EOL>w = v/alpha<EOL>for c, qc in zip(cs, q):<EOL><INDENT>w = axpy(c, w, w.size, -qc)<EOL><DEDENT>return w<EOL>


spsolve = scipy.sparse.linalg.spsolve<EOL>if isinstance(J, Jacobian):<EOL><INDENT>return J<EOL><DEDENT>elif inspect.isclass(J) and issubclass(J, Jacobian):<EOL><INDENT>return J()<EOL><DEDENT>elif isinstance(J, np.ndarray):<EOL><INDENT>if J.ndim > <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>J = np.atleast_2d(np.asarray(J))<EOL>if J.shape[<NUM_LIT:0>] != J.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return Jacobian(matvec=lambda v: dot(J, v),<EOL>rmatvec=lambda v: dot(J.conj().T, v),<EOL>solve=lambda v: solve(J, v),<EOL>rsolve=lambda v: solve(J.conj().T, v),<EOL>dtype=J.dtype, shape=J.shape)<EOL><DEDENT>elif scipy.sparse.isspmatrix(J):<EOL><INDENT>if J.shape[<NUM_LIT:0>] != J.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return Jacobian(matvec=lambda v: J*v,<EOL>rmatvec=lambda v: J.conj().T * v,<EOL>solve=lambda v: spsolve(J, v),<EOL>rsolve=lambda v: spsolve(J.conj().T, v),<EOL>dtype=J.dtype, shape=J.shape)<EOL><DEDENT>elif hasattr(J, '<STR_LIT>') and hasattr(J, '<STR_LIT>') and hasattr(J, '<STR_LIT>'):<EOL><INDENT>return Jacobian(matvec=getattr(J, '<STR_LIT>'),<EOL>rmatvec=getattr(J, '<STR_LIT>'),<EOL>solve=J.solve,<EOL>rsolve=getattr(J, '<STR_LIT>'),<EOL>update=getattr(J, '<STR_LIT>'),<EOL>setup=getattr(J, '<STR_LIT>'),<EOL>dtype=J.dtype,<EOL>shape=J.shape)<EOL><DEDENT>elif callable(J):<EOL><INDENT>class Jac(Jacobian):<EOL><INDENT>def update(self, x, F):<EOL><INDENT>self.x = x<EOL><DEDENT>def solve(self, v, tol=<NUM_LIT:0>):<EOL><INDENT>m = J(self.x)<EOL>if isinstance(m, np.ndarray):<EOL><INDENT>return solve(m, v)<EOL><DEDENT>elif scipy.sparse.isspmatrix(m):<EOL><INDENT>return spsolve(m, v)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>def matvec(self, v):<EOL><INDENT>m = J(self.x)<EOL>if isinstance(m, np.ndarray):<EOL><INDENT>return dot(m, v)<EOL><DEDENT>elif scipy.sparse.isspmatrix(m):<EOL><INDENT>return m*v<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>def rsolve(self, v, tol=<NUM_LIT:0>):<EOL><INDENT>m = J(self.x)<EOL>if isinstance(m, np.ndarray):<EOL><INDENT>return solve(m.conj().T, v)<EOL><DEDENT>elif scipy.sparse.isspmatrix(m):<EOL><INDENT>return spsolve(m.conj().T, v)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>def rmatvec(self, v):<EOL><INDENT>m = J(self.x)<EOL>if isinstance(m, np.ndarray):<EOL><INDENT>return dot(m.conj().T, v)<EOL><DEDENT>elif scipy.sparse.isspmatrix(m):<EOL><INDENT>return m.conj().T * v<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>return Jac()<EOL><DEDENT>elif isinstance(J, str):<EOL><INDENT>return dict(broyden1=BroydenFirst,<EOL>broyden2=BroydenSecond,<EOL>anderson=Anderson,<EOL>diagbroyden=DiagBroyden,<EOL>linearmixing=LinearMixing,<EOL>excitingmixing=ExcitingMixing,<EOL>krylov=KrylovJacobian)[J]()<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>

Convert given object to one suitable for use as a Jacobian.


if self.collapsed is not None:<EOL><INDENT>return solve(self.collapsed.T.conj(), v)<EOL><DEDENT>return LowRankMatrix._solve(v, np.conj(self.alpha), self.ds, self.cs)<EOL>


import inspect<EOL>args, varargs, varkw, defaults = inspect.getargspec(jac.__init__)<EOL>kwargs = list(zip(args[-len(defaults):], defaults))<EOL>kw_str = "<STR_LIT:U+002CU+0020>".join(["<STR_LIT>" % (k, v) for k, v in kwargs])<EOL>if kw_str:<EOL><INDENT>kw_str = "<STR_LIT:U+002CU+0020>" + kw_str<EOL><DEDENT>kwkw_str = "<STR_LIT:U+002CU+0020>".join(["<STR_LIT>" % (k, k) for k, v in kwargs])<EOL>if kwkw_str:<EOL><INDENT>kwkw_str = kwkw_str + "<STR_LIT:U+002CU+0020>"<EOL><DEDENT>wrapper =

Construct a solver wrapper with given name and jacobian approx.

It inspects the keyword arguments of ``jac.__init__``, and allows to
use the same arguments in the wrapper function, in addition to the
keyword arguments of `nonlin_solve`


if self.collapsed is not None:<EOL><INDENT>return solve(self.collapsed, v)<EOL><DEDENT>return LowRankMatrix._solve(v, self.alpha, self.cs, self.ds)<EOL>


def golden(func, args=(), brack=None, tol=_epsilon, full_output=<NUM_LIT:0>):

options = {'<STR_LIT>': tol}<EOL>res = _minimize_scalar_golden(func, brack, args, **options)<EOL>if full_output:<EOL><INDENT>return res['<STR_LIT:x>'], res['<STR_LIT>'], res['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>return res['<STR_LIT:x>']<EOL><DEDENT>

Return the minimum of a function of one variable.

Given a function of one variable and a possible bracketing interval,
return the minimum of the function isolated to a fractional precision of
tol.

Parameters
----------
func : callable func(x,*args)
    Objective function to minimize.
args : tuple
    Additional arguments (if present), passed to func.
brack : tuple
    Triple (a,b,c), where (a<b<c) and func(b) <
    func(a),func(c).  If bracket consists of two numbers (a,
    c), then they are assumed to be a starting interval for a
    downhill bracket search (see `bracket`); it doesn't always
    mean that obtained solution will satisfy a<=x<=c.
tol : float
    x tolerance stop criterion
full_output : bool
    If True, return optional outputs.

See also
--------
minimize_scalar: Interface to minimization algorithms for scalar
    univariate functions. See the 'Golden' `method` in particular.

Notes
-----
Uses analog of bisection method to decrease the bracketed
interval.


def _linesearch_powell(func, p, xi, tol=<NUM_LIT>):

def myfunc(alpha):<EOL><INDENT>return func(p + alpha*xi)<EOL><DEDENT>alpha_min, fret, iter, num = brent(myfunc, full_output=<NUM_LIT:1>, tol=tol)<EOL>xi = alpha_min*xi<EOL>return squeeze(fret), p + xi, xi<EOL>

Line-search algorithm using fminbound.

    Find the minimium of the function ``func(x0+ alpha*direc)``.


def fmin_ncg(f, x0, fprime, fhess_p=None, fhess=None, args=(), avextol=<NUM_LIT>,<EOL>epsilon=_epsilon, maxiter=None, full_output=<NUM_LIT:0>, disp=<NUM_LIT:1>, retall=<NUM_LIT:0>,<EOL>callback=None):

opts = {'<STR_LIT>': avextol,<EOL>'<STR_LIT>': epsilon,<EOL>'<STR_LIT>': maxiter,<EOL>'<STR_LIT>': disp,<EOL>'<STR_LIT>': retall}<EOL>res = _minimize_newtoncg(f, x0, args, fprime, fhess, fhess_p,<EOL>callback=callback, **opts)<EOL>if full_output:<EOL><INDENT>retlist = (res['<STR_LIT:x>'], res['<STR_LIT>'], res['<STR_LIT>'], res['<STR_LIT>'],<EOL>res['<STR_LIT>'], res['<STR_LIT:status>'])<EOL>if retall:<EOL><INDENT>retlist += (res['<STR_LIT>'], )<EOL><DEDENT>return retlist<EOL><DEDENT>else:<EOL><INDENT>if retall:<EOL><INDENT>return res['<STR_LIT:x>'], res['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>return res['<STR_LIT:x>']<EOL><DEDENT><DEDENT>

Unconstrained minimization of a function using the Newton-CG method.

Parameters
----------
f : callable ``f(x, *args)``
    Objective function to be minimized.
x0 : ndarray
    Initial guess.
fprime : callable ``f'(x, *args)``
    Gradient of f.
fhess_p : callable ``fhess_p(x, p, *args)``, optional
    Function which computes the Hessian of f times an
    arbitrary vector, p.
fhess : callable ``fhess(x, *args)``, optional
    Function to compute the Hessian matrix of f.
args : tuple, optional
    Extra arguments passed to f, fprime, fhess_p, and fhess
    (the same set of extra arguments is supplied to all of
    these functions).
epsilon : float or ndarray, optional
    If fhess is approximated, use this value for the step size.
callback : callable, optional
    An optional user-supplied function which is called after
    each iteration.  Called as callback(xk), where xk is the
    current parameter vector.
avextol : float, optional
    Convergence is assumed when the average relative error in
    the minimizer falls below this amount.
maxiter : int, optional
    Maximum number of iterations to perform.
full_output : bool, optional
    If True, return the optional outputs.
disp : bool, optional
    If True, print convergence message.
retall : bool, optional
    If True, return a list of results at each iteration.

Returns
-------
xopt : ndarray
    Parameters which minimize f, i.e. ``f(xopt) == fopt``.
fopt : float
    Value of the function at xopt, i.e. ``fopt = f(xopt)``.
fcalls : int
    Number of function calls made.
gcalls : int
    Number of gradient calls made.
hcalls : int
    Number of hessian calls made.
warnflag : int
    Warnings generated by the algorithm.
    1 : Maximum number of iterations exceeded.
allvecs : list
    The result at each iteration, if retall is True (see below).

See also
--------
minimize: Interface to minimization algorithms for multivariate
    functions. See the 'Newton-CG' `method` in particular.

Notes
-----
Only one of `fhess_p` or `fhess` need to be given.  If `fhess`
is provided, then `fhess_p` will be ignored.  If neither `fhess`
nor `fhess_p` is provided, then the hessian product will be
approximated using finite differences on `fprime`. `fhess_p`
must compute the hessian times an arbitrary vector. If it is not
given, finite-differences on `fprime` are used to compute
it.

Newton-CG methods are also called truncated Newton methods. This
function differs from scipy.optimize.fmin_tnc because

1. scipy.optimize.fmin_ncg is written purely in python using numpy
    and scipy while scipy.optimize.fmin_tnc calls a C function.
2. scipy.optimize.fmin_ncg is only for unconstrained minimization
    while scipy.optimize.fmin_tnc is for unconstrained minimization
    or box constrained minimization. (Box constraints give
    lower and upper bounds for each variable separately.)

References
----------
Wright & Nocedal, 'Numerical Optimization', 1999, pg. 140.


def brent(func, args=(), brack=None, tol=<NUM_LIT>, full_output=<NUM_LIT:0>, maxiter=<NUM_LIT>):

options = {'<STR_LIT>': tol,<EOL>'<STR_LIT>': maxiter}<EOL>res = _minimize_scalar_brent(func, brack, args, **options)<EOL>if full_output:<EOL><INDENT>return res['<STR_LIT:x>'], res['<STR_LIT>'], res['<STR_LIT>'], res['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>return res['<STR_LIT:x>']<EOL><DEDENT>

Given a function of one-variable and a possible bracketing interval,
return the minimum of the function isolated to a fractional precision of
tol.

Parameters
----------
func : callable f(x,*args)
    Objective function.
args
    Additional arguments (if present).
brack : tuple
    Triple (a,b,c) where (a<b<c) and func(b) <
    func(a),func(c).  If bracket consists of two numbers (a,c)
    then they are assumed to be a starting interval for a
    downhill bracket search (see `bracket`); it doesn't always
    mean that the obtained solution will satisfy a<=x<=c.
tol : float
    Stop if between iteration change is less than `tol`.
full_output : bool
    If True, return all output args (xmin, fval, iter,
    funcalls).
maxiter : int
    Maximum number of iterations in solution.

Returns
-------
xmin : ndarray
    Optimum point.
fval : float
    Optimum value.
iter : int
    Number of iterations.
funcalls : int
    Number of objective function evaluations made.

See also
--------
minimize_scalar: Interface to minimization algorithms for scalar
    univariate functions. See the 'Brent' `method` in particular.

Notes
-----
Uses inverse parabolic interpolation when possible to speed up
convergence of golden section method.


def root(fun, x0, args=(), method='<STR_LIT>', jac=None, tol=None, callback=None,<EOL>options=None):

if not isinstance(args, tuple):<EOL><INDENT>args = (args,)<EOL><DEDENT>meth = method.lower()<EOL>if options is None:<EOL><INDENT>options = {}<EOL><DEDENT>if callback is not None and meth in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>warn('<STR_LIT>' % method,<EOL>RuntimeWarning)<EOL><DEDENT>if not callable(jac) and meth in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if bool(jac):<EOL><INDENT>fun = MemoizeJac(fun)<EOL>jac = fun.derivative<EOL><DEDENT>else:<EOL><INDENT>jac = None<EOL><DEDENT><DEDENT>if tol is not None:<EOL><INDENT>options = dict(options)<EOL>if meth in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>options.setdefault('<STR_LIT>', tol)<EOL><DEDENT>elif meth in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>options.setdefault('<STR_LIT>', tol)<EOL>options.setdefault('<STR_LIT>', np.inf)<EOL>options.setdefault('<STR_LIT>', np.inf)<EOL>options.setdefault('<STR_LIT>', np.inf)<EOL><DEDENT><DEDENT>if meth == '<STR_LIT>':<EOL><INDENT>sol = _root_hybr(fun, x0, args=args, jac=jac, **options)<EOL><DEDENT>elif meth == '<STR_LIT>':<EOL><INDENT>sol = _root_leastsq(fun, x0, args=args, jac=jac, **options)<EOL><DEDENT>elif meth in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if jac is not None:<EOL><INDENT>warn('<STR_LIT>' % method,<EOL>RuntimeWarning)<EOL><DEDENT>sol = _root_nonlin_solve(fun, x0, args=args, jac=jac,<EOL>_method=meth, _callback=callback,<EOL>**options)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % method)<EOL><DEDENT>return sol<EOL>

Find a root of a vector function.

Parameters
----------
fun : callable
    A vector function to find a root of.
x0 : ndarray
    Initial guess.
args : tuple, optional
    Extra arguments passed to the objective function and its Jacobian.
method : str, optional
    Type of solver.  Should be one of

        - 'hybr'
        - 'lm'
        - 'broyden1'
        - 'broyden2'
        - 'anderson'
        - 'linearmixing'
        - 'diagbroyden'
        - 'excitingmixing'
        - 'krylov'

jac : bool or callable, optional
    If `jac` is a Boolean and is True, `fun` is assumed to return the
    value of Jacobian along with the objective function. If False, the
    Jacobian will be estimated numerically.
    `jac` can also be a callable returning the Jacobian of `fun`. In
    this case, it must accept the same arguments as `fun`.
tol : float, optional
    Tolerance for termination. For detailed control, use solver-specific
    options.
callback : function, optional
    Optional callback function. It is called on every iteration as
    ``callback(x, f)`` where `x` is the current solution and `f`
    the corresponding residual. For all methods but 'hybr' and 'lm'.
options : dict, optional
    A dictionary of solver options. E.g. `xtol` or `maxiter`, see
    :obj:`show_options()` for details.

Returns
-------
sol : OptimizeResult
    The solution represented as a ``OptimizeResult`` object.
    Important attributes are: ``x`` the solution array, ``success`` a
    Boolean flag indicating if the algorithm exited successfully and
    ``message`` which describes the cause of the termination. See
    `OptimizeResult` for a description of other attributes.

See also
--------
show_options : Additional options accepted by the solvers

Notes
-----
This section describes the available solvers that can be selected by the
'method' parameter. The default method is *hybr*.

Method *hybr* uses a modification of the Powell hybrid method as
implemented in MINPACK [1]_.

Method *lm* solves the system of nonlinear equations in a least squares
sense using a modification of the Levenberg-Marquardt algorithm as
implemented in MINPACK [1]_.

Methods *broyden1*, *broyden2*, *anderson*, *linearmixing*,
*diagbroyden*, *excitingmixing*, *krylov* are inexact Newton methods,
with backtracking or full line searches [2]_. Each method corresponds
to a particular Jacobian approximations. See `nonlin` for details.

- Method *broyden1* uses Broyden's first Jacobian approximation, it is
  known as Broyden's good method.
- Method *broyden2* uses Broyden's second Jacobian approximation, it
  is known as Broyden's bad method.
- Method *anderson* uses (extended) Anderson mixing.
- Method *Krylov* uses Krylov approximation for inverse Jacobian. It
  is suitable for large-scale problem.
- Method *diagbroyden* uses diagonal Broyden Jacobian approximation.
- Method *linearmixing* uses a scalar Jacobian approximation.
- Method *excitingmixing* uses a tuned diagonal Jacobian
  approximation.

.. warning::

    The algorithms implemented for methods *diagbroyden*,
    *linearmixing* and *excitingmixing* may be useful for specific
    problems, but whether they will work may depend strongly on the
    problem.

.. versionadded:: 0.11.0

References
----------
.. [1] More, Jorge J., Burton S. Garbow, and Kenneth E. Hillstrom.
   1980. User Guide for MINPACK-1.
.. [2] C. T. Kelley. 1995. Iterative Methods for Linear and Nonlinear
    Equations. Society for Industrial and Applied Mathematics.
    <http://www.siam.org/books/kelley/>

Examples
--------
The following functions define a system of nonlinear equations and its
jacobian.

>>> def fun(x):
...     return [x[0]  + 0.5 * (x[0] - x[1])**3 - 1.0,
...             0.5 * (x[1] - x[0])**3 + x[1]]

>>> def jac(x):
...     return np.array([[1 + 1.5 * (x[0] - x[1])**2,
...                       -1.5 * (x[0] - x[1])**2],
...                      [-1.5 * (x[1] - x[0])**2,
...                       1 + 1.5 * (x[1] - x[0])**2]])

A solution can be obtained as follows.

>>> from scipy import optimize
>>> sol = optimize.root(fun, [0, 0], jac=jac, method='hybr')
>>> sol.x
array([ 0.8411639,  0.1588361])


def fmin_cobyla(func, x0, cons, args=(), consargs=None, rhobeg=<NUM_LIT:1.0>,<EOL>rhoend=<NUM_LIT>, iprint=<NUM_LIT:1>, maxfun=<NUM_LIT:1000>, disp=None, catol=<NUM_LIT>):

err = "<STR_LIT>""<STR_LIT>"<EOL>try:<EOL><INDENT>len(cons)<EOL><DEDENT>except TypeError:<EOL><INDENT>if callable(cons):<EOL><INDENT>cons = [cons]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(err)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for thisfunc in cons:<EOL><INDENT>if not callable(thisfunc):<EOL><INDENT>raise TypeError(err)<EOL><DEDENT><DEDENT><DEDENT>if consargs is None:<EOL><INDENT>consargs = args<EOL><DEDENT>con = tuple({'<STR_LIT:type>': '<STR_LIT>', '<STR_LIT>': c, '<STR_LIT:args>': consargs} for c in cons)<EOL>if disp is not None:<EOL><INDENT>iprint = disp<EOL><DEDENT>opts = {'<STR_LIT>': rhobeg,<EOL>'<STR_LIT>': rhoend,<EOL>'<STR_LIT>': iprint,<EOL>'<STR_LIT>': iprint != <NUM_LIT:0>,<EOL>'<STR_LIT>': maxfun,<EOL>'<STR_LIT>': catol}<EOL>sol = _minimize_cobyla(func, x0, args, constraints=con,<EOL>**opts)<EOL>if iprint > <NUM_LIT:0> and not sol['<STR_LIT:success>']:<EOL><INDENT>print("<STR_LIT>" % (sol.message,))<EOL><DEDENT>return sol['<STR_LIT:x>']<EOL>

Minimize a function using the Constrained Optimization BY Linear
Approximation (COBYLA) method. This method wraps a FORTRAN
implentation of the algorithm.

Parameters
----------
func : callable
    Function to minimize. In the form func(x, \\*args).
x0 : ndarray
    Initial guess.
cons : sequence
    Constraint functions; must all be ``>=0`` (a single function
    if only 1 constraint). Each function takes the parameters `x`
    as its first argument.
args : tuple
    Extra arguments to pass to function.
consargs : tuple
    Extra arguments to pass to constraint functions (default of None means
    use same extra arguments as those passed to func).
    Use ``()`` for no extra arguments.
rhobeg :
    Reasonable initial changes to the variables.
rhoend :
    Final accuracy in the optimization (not precisely guaranteed). This
    is a lower bound on the size of the trust region.
iprint : {0, 1, 2, 3}
    Controls the frequency of output; 0 implies no output.  Deprecated.
disp : {0, 1, 2, 3}
    Over-rides the iprint interface.  Preferred.
maxfun : int
    Maximum number of function evaluations.
catol : float
    Absolute tolerance for constraint violations.

Returns
-------
x : ndarray
    The argument that minimises `f`.

See also
--------
minimize: Interface to minimization algorithms for multivariate
    functions. See the 'COBYLA' `method` in particular.

Notes
-----
This algorithm is based on linear approximations to the objective
function and each constraint. We briefly describe the algorithm.

Suppose the function is being minimized over k variables. At the
jth iteration the algorithm has k+1 points v_1, ..., v_(k+1),
an approximate solution x_j, and a radius RHO_j.
(i.e. linear plus a constant) approximations to the objective
function and constraint functions such that their function values
agree with the linear approximation on the k+1 points v_1,.., v_(k+1).
This gives a linear program to solve (where the linear approximations
of the constraint functions are constrained to be non-negative).

However the linear approximations are likely only good
approximations near the current simplex, so the linear program is
given the further requirement that the solution, which
will become x_(j+1), must be within RHO_j from x_j. RHO_j only
decreases, never increases. The initial RHO_j is rhobeg and the
final RHO_j is rhoend. In this way COBYLA's iterations behave
like a trust region algorithm.

Additionally, the linear program may be inconsistent, or the
approximation may give poor improvement. For details about
how these issues are resolved, as well as how the points v_i are
updated, refer to the source code or the references below.

References
----------
Powell M.J.D. (1994), "A direct search optimization method that models
the objective and constraint functions by linear interpolation.", in
Advances in Optimization and Numerical Analysis, eds. S. Gomez and
J-P Hennart, Kluwer Academic (Dordrecht), pp. 51-67

Powell M.J.D. (1998), "Direct search algorithms for optimization
calculations", Acta Numerica 7, 287-336

Powell M.J.D. (2007), "A view of algorithms for optimization without
derivatives", Cambridge University Technical Report DAMTP 2007/NA03

Examples
--------
Minimize the objective function f(x,y) = x*y subject
to the constraints x**2 + y**2 < 1 and y > 0::

    >>> def objective(x):
    ...     return x[0]*x[1]
    ...
    >>> def constr1(x):
    ...     return 1 - (x[0]**2 + x[1]**2)
    ...
    >>> def constr2(x):
    ...     return x[1]
    ...
    >>> fmin_cobyla(objective, [0.0, 0.1], [constr1, constr2], rhoend=1e-7)

       Normal return from subroutine COBYLA

       NFVALS =   64   F =-5.000000E-01    MAXCV = 1.998401E-14
       X =-7.071069E-01   7.071067E-01
    array([-0.70710685,  0.70710671])

The exact solution is (-sqrt(2)/2, sqrt(2)/2).


results = self.average_results()<EOL>results = sorted(results, key=lambda x: (x.nfail, x.mean_time))<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>" % (self.function_name))<EOL>print("<STR_LIT>" % (results[<NUM_LIT:0>].ndim, str(self.minimizer_kwargs)))<EOL>print("<STR_LIT>" % (results[<NUM_LIT:0>].ntrials))<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>for res in results:<EOL><INDENT>print("<STR_LIT>" %<EOL>(res.name, res.nfail, res.mean_nfev, res.mean_njev, res.mean_nhev, res.mean_time))<EOL><DEDENT>


result.time = t<EOL>result.name = name<EOL>if not hasattr(result, "<STR_LIT>"):<EOL><INDENT>result.njev = <NUM_LIT:0><EOL><DEDENT>if not hasattr(result, "<STR_LIT>"):<EOL><INDENT>result.nhev = <NUM_LIT:0><EOL><DEDENT>self.results.append(result)<EOL>