if any(alpha <= -<NUM_LIT:1>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if n < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if n == <NUM_LIT:0>:<EOL><INDENT>n1 = n + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>n1 = n<EOL><DEDENT>x, w, mu0 = la_roots(n1, alpha, mu=True)<EOL>wfunc = lambda x: exp(-x) * x**alpha<EOL>if n == <NUM_LIT:0>:<EOL><INDENT>x, w = [], []<EOL><DEDENT>hn = _gam(n + alpha + <NUM_LIT:1>) / _gam(n + <NUM_LIT:1>)<EOL>kn = (-<NUM_LIT:1>)**n / _gam(n + <NUM_LIT:1>)<EOL>p = orthopoly1d(x, w, hn, kn, wfunc, (<NUM_LIT:0>, inf), monic,<EOL>lambda x: eval_genlaguerre(n, alpha, x))<EOL>return p<EOL>

Returns the nth order generalized (associated) Laguerre polynomial,
    L^(alpha)_n(x), orthogonal over [0,inf) with weighting function
    exp(-x) x**alpha with alpha > -1


def jacobi(n, alpha, beta, monic=False):

if n < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>wfunc = lambda x: (<NUM_LIT:1> - x)**alpha * (<NUM_LIT:1> + x)**beta<EOL>if n == <NUM_LIT:0>:<EOL><INDENT>return orthopoly1d([], [], <NUM_LIT:1.0>, <NUM_LIT:1.0>, wfunc, (-<NUM_LIT:1>, <NUM_LIT:1>), monic,<EOL>eval_func=np.ones_like)<EOL><DEDENT>x, w, mu = j_roots(n, alpha, beta, mu=True)<EOL>ab1 = alpha + beta + <NUM_LIT:1.0><EOL>hn = <NUM_LIT:2>**ab1 / (<NUM_LIT:2> * n + ab1) * _gam(n + alpha + <NUM_LIT:1>)<EOL>hn *= _gam(n + beta + <NUM_LIT:1.0>) / _gam(n + <NUM_LIT:1>) / _gam(n + ab1)<EOL>kn = _gam(<NUM_LIT:2> * n + ab1) / <NUM_LIT>**n / _gam(n + <NUM_LIT:1>) / _gam(n + ab1)<EOL>p = orthopoly1d(x, w, hn, kn, wfunc, (-<NUM_LIT:1>, <NUM_LIT:1>), monic,<EOL>lambda x: eval_jacobi(n, alpha, beta, x))<EOL>return p<EOL>

Returns the nth order Jacobi polynomial, P^(alpha,beta)_n(x)
    orthogonal over [-1,1] with weighting function
    (1-x)**alpha (1+x)**beta with alpha,beta > -1.


def _dct(x, type, n=None, axis=-<NUM_LIT:1>, overwrite_x=False, normalize=None):

tmp = np.asarray(x)<EOL>if not np.isrealobj(tmp):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if n is None:<EOL><INDENT>n = tmp.shape[axis]<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>if tmp.dtype == np.double:<EOL><INDENT>if type == <NUM_LIT:1>:<EOL><INDENT>f = _fftpack.ddct1<EOL><DEDENT>elif type == <NUM_LIT:2>:<EOL><INDENT>f = _fftpack.ddct2<EOL><DEDENT>elif type == <NUM_LIT:3>:<EOL><INDENT>f = _fftpack.ddct3<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % type)<EOL><DEDENT><DEDENT>elif tmp.dtype == np.float32:<EOL><INDENT>if type == <NUM_LIT:1>:<EOL><INDENT>f = _fftpack.dct1<EOL><DEDENT>elif type == <NUM_LIT:2>:<EOL><INDENT>f = _fftpack.dct2<EOL><DEDENT>elif type == <NUM_LIT:3>:<EOL><INDENT>f = _fftpack.dct3<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % type)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % tmp.dtype)<EOL><DEDENT>if normalize:<EOL><INDENT>if normalize == "<STR_LIT>":<EOL><INDENT>nm = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % normalize)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>nm = <NUM_LIT:0><EOL><DEDENT>if type == <NUM_LIT:1> and n < <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>overwrite_x = overwrite_x or _datacopied(tmp, x)<EOL>if axis == -<NUM_LIT:1> or axis == len(tmp.shape) - <NUM_LIT:1>:<EOL><INDENT>return f(tmp, n, nm, overwrite_x)<EOL><DEDENT>tmp = np.swapaxes(tmp, axis, -<NUM_LIT:1>)<EOL>tmp = f(tmp, n, nm, overwrite_x)<EOL>return np.swapaxes(tmp, axis, -<NUM_LIT:1>)<EOL>

Return Discrete Cosine Transform of arbitrary type sequence x.

Parameters
----------
x : array-like
    input array.
n : int, optional
    Length of the transform.
axis : int, optional
    Axis along which the dct is computed. (default=-1)
overwrite_x : bool, optional
    If True the contents of x can be destroyed. (default=False)

Returns
-------
z : real ndarray


def ifft(x, n=None, axis=-<NUM_LIT:1>, overwrite_x=False):

tmp = _asfarray(x)<EOL>try:<EOL><INDENT>work_function = _DTYPE_TO_FFT[tmp.dtype]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>" % tmp.dtype)<EOL><DEDENT>if not (istype(tmp, numpy.complex64) or istype(tmp, numpy.complex128)):<EOL><INDENT>overwrite_x = <NUM_LIT:1><EOL><DEDENT>overwrite_x = overwrite_x or _datacopied(tmp, x)<EOL>if n is None:<EOL><INDENT>n = tmp.shape[axis]<EOL><DEDENT>elif n != tmp.shape[axis]:<EOL><INDENT>tmp, copy_made = _fix_shape(tmp,n,axis)<EOL>overwrite_x = overwrite_x or copy_made<EOL><DEDENT>if n < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % n)<EOL><DEDENT>if axis == -<NUM_LIT:1> or axis == len(tmp.shape) - <NUM_LIT:1>:<EOL><INDENT>return work_function(tmp,n,-<NUM_LIT:1>,<NUM_LIT:1>,overwrite_x)<EOL><DEDENT>tmp = swapaxes(tmp, axis, -<NUM_LIT:1>)<EOL>tmp = work_function(tmp,n,-<NUM_LIT:1>,<NUM_LIT:1>,overwrite_x)<EOL>return swapaxes(tmp, axis, -<NUM_LIT:1>)<EOL>

Return discrete inverse Fourier transform of real or complex sequence.

The returned complex array contains ``y(0), y(1),..., y(n-1)`` where

``y(j) = (x * exp(2*pi*sqrt(-1)*j*np.arange(n)/n)).mean()``.

Parameters
----------
x : array_like
    Transformed data to invert.
n : int, optional
    Length of the inverse Fourier transform.  If ``n < x.shape[axis]``,
    `x` is truncated.  If ``n > x.shape[axis]``, `x` is zero-padded.
    The default results in ``n = x.shape[axis]``.
axis : int, optional
    Axis along which the ifft's are computed; the default is over the
    last axis (i.e., ``axis=-1``).
overwrite_x : bool, optional
    If True, the contents of `x` can be destroyed; the default is False.

Returns
-------
ifft : ndarray of floats
    The inverse discrete Fourier transform.

See Also
--------
fft : Forward FFT

Notes
-----
This function is most efficient when `n` is a power of two, and least
efficient when `n` is prime.

If the data type of `x` is real, a "real IFFT" algorithm is automatically
used, which roughly halves the computation time.


def fft2(x, shape=None, axes=(-<NUM_LIT:2>,-<NUM_LIT:1>), overwrite_x=False):

return fftn(x,shape,axes,overwrite_x)<EOL>

2-D discrete Fourier transform.

Return the two-dimensional discrete Fourier transform of the 2-D argument
`x`.

See Also
--------
fftn : for detailed information.


def ifftn(x, shape=None, axes=None, overwrite_x=False):

return _raw_fftn_dispatch(x, shape, axes, overwrite_x, -<NUM_LIT:1>)<EOL>

Return inverse multi-dimensional discrete Fourier transform of
arbitrary type sequence x.

The returned array contains::

  y[j_1,..,j_d] = 1/p * sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
     x[k_1,..,k_d] * prod[i=1..d] exp(sqrt(-1)*2*pi/n_i * j_i * k_i)

where ``d = len(x.shape)``, ``n = x.shape``, and ``p = prod[i=1..d] n_i``.

For description of parameters see `fftn`.

See Also
--------
fftn : for detailed information.


n = int(n)<EOL>if n == <NUM_LIT:0>:<EOL><INDENT>return True<EOL><DEDENT>for c in (<NUM_LIT:3>, <NUM_LIT:5>):<EOL><INDENT>while n % c == <NUM_LIT:0>:<EOL><INDENT>n //= c<EOL><DEDENT><DEDENT>return not n & (n-<NUM_LIT:1>)<EOL>

Is the size of FFT such that FFTPACK can handle it in single precision
with sufficient accuracy?

Composite numbers of 2, 3, and 5 are accepted, as FFTPACK has those


def fft(x, n=None, axis=-<NUM_LIT:1>, overwrite_x=False):

tmp = _asfarray(x)<EOL>try:<EOL><INDENT>work_function = _DTYPE_TO_FFT[tmp.dtype]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>" % tmp.dtype)<EOL><DEDENT>if not (istype(tmp, numpy.complex64) or istype(tmp, numpy.complex128)):<EOL><INDENT>overwrite_x = <NUM_LIT:1><EOL><DEDENT>overwrite_x = overwrite_x or _datacopied(tmp, x)<EOL>if n is None:<EOL><INDENT>n = tmp.shape[axis]<EOL><DEDENT>elif n != tmp.shape[axis]:<EOL><INDENT>tmp, copy_made = _fix_shape(tmp,n,axis)<EOL>overwrite_x = overwrite_x or copy_made<EOL><DEDENT>if n < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % n)<EOL><DEDENT>if axis == -<NUM_LIT:1> or axis == len(tmp.shape) - <NUM_LIT:1>:<EOL><INDENT>return work_function(tmp,n,<NUM_LIT:1>,<NUM_LIT:0>,overwrite_x)<EOL><DEDENT>tmp = swapaxes(tmp, axis, -<NUM_LIT:1>)<EOL>tmp = work_function(tmp,n,<NUM_LIT:1>,<NUM_LIT:0>,overwrite_x)<EOL>return swapaxes(tmp, axis, -<NUM_LIT:1>)<EOL>

Return discrete Fourier transform of real or complex sequence.

The returned complex array contains ``y(0), y(1),..., y(n-1)`` where

``y(j) = (x * exp(-2*pi*sqrt(-1)*j*np.arange(n)/n)).sum()``.

Parameters
----------
x : array_like
    Array to Fourier transform.
n : int, optional
    Length of the Fourier transform.  If ``n < x.shape[axis]``, `x` is
    truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
    default results in ``n = x.shape[axis]``.
axis : int, optional
    Axis along which the fft's are computed; the default is over the
    last axis (i.e., ``axis=-1``).
overwrite_x : bool, optional
    If True, the contents of `x` can be destroyed; the default is False.

Returns
-------
z : complex ndarray
    with the elements::

        [y(0),y(1),..,y(n/2),y(1-n/2),...,y(-1)]        if n is even
        [y(0),y(1),..,y((n-1)/2),y(-(n-1)/2),...,y(-1)]  if n is odd

    where::

        y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n), j = 0..n-1

    Note that ``y(-j) = y(n-j).conjugate()``.

See Also
--------
ifft : Inverse FFT
rfft : FFT of a real sequence

Notes
-----
The packing of the result is "standard": If ``A = fft(a, n)``, then
``A[0]`` contains the zero-frequency term, ``A[1:n/2]`` contains the
positive-frequency terms, and ``A[n/2:]`` contains the negative-frequency
terms, in order of decreasingly negative frequency. So for an 8-point
transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1].
To rearrange the fft output so that the zero-frequency component is
centered, like [-4, -3, -2, -1,  0,  1,  2,  3], use `fftshift`.

For `n` even, ``A[n/2]`` contains the sum of the positive and
negative-frequency terms.  For `n` even and `x` real, ``A[n/2]`` will
always be real.

This function is most efficient when `n` is a power of two, and least
efficient when `n` is prime.

If the data type of `x` is real, a "real FFT" algorithm is automatically
used, which roughly halves the computation time.  To increase efficiency
a little further, use `rfft`, which does the same calculation, but only
outputs half of the symmetrical spectrum.  If the data is both real and
symmetrical, the `dct` can again double the efficiency, by generating
half of the spectrum from half of the signal.

Examples
--------
>>> from scipy.fftpack import fft, ifft
>>> x = np.arange(5)
>>> np.allclose(fft(ifft(x)), x, atol=1e-15)  # within numerical accuracy.
True


def cc_diff(x, a, b, period=None, _cache=_cache):

tmp = asarray(x)<EOL>if iscomplexobj(tmp):<EOL><INDENT>return cc_diff(tmp.real,a,b,period) +<NUM_LIT>*cc_diff(tmp.imag,a,b,period)<EOL><DEDENT>if period is not None:<EOL><INDENT>a = a*<NUM_LIT:2>*pi/period<EOL>b = b*<NUM_LIT:2>*pi/period<EOL><DEDENT>n = len(x)<EOL>omega = _cache.get((n,a,b))<EOL>if omega is None:<EOL><INDENT>if len(_cache) > <NUM_LIT:20>:<EOL><INDENT>while _cache:<EOL><INDENT>_cache.popitem()<EOL><DEDENT><DEDENT>def kernel(k,a=a,b=b):<EOL><INDENT>return cosh(a*k)/cosh(b*k)<EOL><DEDENT>omega = convolve.init_convolution_kernel(n,kernel)<EOL>_cache[(n,a,b)] = omega<EOL><DEDENT>overwrite_x = _datacopied(tmp, x)<EOL>return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)<EOL>

Return (a,b)-cosh/cosh pseudo-derivative of a periodic sequence.

If x_j and y_j are Fourier coefficients of periodic functions x
and y, respectively, then::

  y_j = cosh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j

Parameters
----------
x : array_like
    The array to take the pseudo-derivative from.
a,b : float
    Defines the parameters of the sinh/sinh pseudo-differential
    operator.
period : float, optional
    The period of the sequence x. Default is ``2*pi``.

Returns
-------
cc_diff : ndarray
    Pseudo-derivative of periodic sequence `x`.

Notes
-----
``cc_diff(cc_diff(x,a,b),b,a) == x``


def ss_diff(x, a, b, period=None, _cache=_cache):

tmp = asarray(x)<EOL>if iscomplexobj(tmp):<EOL><INDENT>return ss_diff(tmp.real,a,b,period) +<NUM_LIT>*ss_diff(tmp.imag,a,b,period)<EOL><DEDENT>if period is not None:<EOL><INDENT>a = a*<NUM_LIT:2>*pi/period<EOL>b = b*<NUM_LIT:2>*pi/period<EOL><DEDENT>n = len(x)<EOL>omega = _cache.get((n,a,b))<EOL>if omega is None:<EOL><INDENT>if len(_cache) > <NUM_LIT:20>:<EOL><INDENT>while _cache:<EOL><INDENT>_cache.popitem()<EOL><DEDENT><DEDENT>def kernel(k,a=a,b=b):<EOL><INDENT>if k:<EOL><INDENT>return sinh(a*k)/sinh(b*k)<EOL><DEDENT>return float(a)/b<EOL><DEDENT>omega = convolve.init_convolution_kernel(n,kernel)<EOL>_cache[(n,a,b)] = omega<EOL><DEDENT>overwrite_x = _datacopied(tmp, x)<EOL>return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)<EOL>

Return (a,b)-sinh/sinh pseudo-derivative of a periodic sequence x.

If x_j and y_j are Fourier coefficients of periodic functions x
and y, respectively, then::

  y_j = sinh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
  y_0 = a/b * x_0

Parameters
----------
x : array_like
    The array to take the pseudo-derivative from.
a,b
    Defines the parameters of the sinh/sinh pseudo-differential
    operator.
period : float, optional
    The period of the sequence x. Default is ``2*pi``.

Notes
-----
``ss_diff(ss_diff(x,a,b),b,a) == x``


tmp = asarray(x)<EOL>if iscomplexobj(tmp):<EOL><INDENT>return hilbert(tmp.real)+<NUM_LIT>*hilbert(tmp.imag)<EOL><DEDENT>n = len(x)<EOL>omega = _cache.get(n)<EOL>if omega is None:<EOL><INDENT>if len(_cache) > <NUM_LIT:20>:<EOL><INDENT>while _cache:<EOL><INDENT>_cache.popitem()<EOL><DEDENT><DEDENT>def kernel(k):<EOL><INDENT>if k > <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:1.0><EOL><DEDENT>elif k < <NUM_LIT:0>:<EOL><INDENT>return -<NUM_LIT:1.0><EOL><DEDENT>return <NUM_LIT:0.0><EOL><DEDENT>omega = convolve.init_convolution_kernel(n,kernel,d=<NUM_LIT:1>)<EOL>_cache[n] = omega<EOL><DEDENT>overwrite_x = _datacopied(tmp, x)<EOL>return convolve.convolve(tmp,omega,swap_real_imag=<NUM_LIT:1>,overwrite_x=overwrite_x)<EOL>

Return Hilbert transform of a periodic sequence x.

If x_j and y_j are Fourier coefficients of periodic functions x
and y, respectively, then::

  y_j = sqrt(-1)*sign(j) * x_j
  y_0 = 0

Parameters
----------
x : array_like
    The input array, should be periodic.
_cache : dict, optional
    Dictionary that contains the kernel used to do a convolution with.

Returns
-------
y : ndarray
    The transformed input.

Notes
-----
If ``sum(x, axis=0) == 0`` then ``hilbert(ihilbert(x)) == x``.

For even len(x), the Nyquist mode of x is taken zero.

The sign of the returned transform does not have a factor -1 that is more
often than not found in the definition of the Hilbert transform.  Note also
that ``scipy.signal.hilbert`` does have an extra -1 factor compared to this
function.


self.meta.update(kwds)<EOL>

Update the metadata dictionary with the keywords and data provided
        by keywords.

        Examples
        --------
        >>> data.set_meta(lab="Ph 7; Lab 26", title="Ag110 + Ag108 Decay")


args = (self.model.fcn, self.beta0, self.data.y, self.data.x)<EOL>kwds = {'<STR_LIT>': <NUM_LIT:1>}<EOL>kwd_l = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if self.delta0 is not None and self.job % <NUM_LIT:1000> // <NUM_LIT:10> == <NUM_LIT:1>:<EOL><INDENT>self._gen_work()<EOL>d0 = numpy.ravel(self.delta0)<EOL>self.work[:len(d0)] = d0<EOL><DEDENT>if self.model.fjacb is not None:<EOL><INDENT>kwds['<STR_LIT>'] = self.model.fjacb<EOL><DEDENT>if self.model.fjacd is not None:<EOL><INDENT>kwds['<STR_LIT>'] = self.model.fjacd<EOL><DEDENT>if self.data.we is not None:<EOL><INDENT>kwds['<STR_LIT>'] = self.data.we<EOL><DEDENT>if self.data.wd is not None:<EOL><INDENT>kwds['<STR_LIT>'] = self.data.wd<EOL><DEDENT>if self.model.extra_args is not None:<EOL><INDENT>kwds['<STR_LIT>'] = self.model.extra_args<EOL><DEDENT>for attr in kwd_l:<EOL><INDENT>obj = getattr(self, attr)<EOL>if obj is not None:<EOL><INDENT>kwds[attr] = obj<EOL><DEDENT><DEDENT>self.output = Output(odr(*args, **kwds))<EOL>return self.output<EOL>

Run the fitting routine with all of the information given.

        Returns
        -------
        output : Output instance
            This object is also assigned to the attribute .output .


x_s = list(self.data.x.shape)<EOL>if isinstance(self.data.y, numpy.ndarray):<EOL><INDENT>y_s = list(self.data.y.shape)<EOL>if self.model.implicit:<EOL><INDENT>raise odr_error("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>y_s = [self.data.y, x_s[-<NUM_LIT:1>]]<EOL>if not self.model.implicit:<EOL><INDENT>raise odr_error("<STR_LIT>")<EOL><DEDENT>self.set_job(fit_type=<NUM_LIT:1>)<EOL><DEDENT>if x_s[-<NUM_LIT:1>] != y_s[-<NUM_LIT:1>]:<EOL><INDENT>raise odr_error("<STR_LIT>")<EOL><DEDENT>n = x_s[-<NUM_LIT:1>]<EOL>if len(x_s) == <NUM_LIT:2>:<EOL><INDENT>m = x_s[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>m = <NUM_LIT:1><EOL><DEDENT>if len(y_s) == <NUM_LIT:2>:<EOL><INDENT>q = y_s[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>q = <NUM_LIT:1><EOL><DEDENT>p = len(self.beta0)<EOL>fcn_perms = [(q, n)]<EOL>fjacd_perms = [(q, m, n)]<EOL>fjacb_perms = [(q, p, n)]<EOL>if q == <NUM_LIT:1>:<EOL><INDENT>fcn_perms.append((n,))<EOL>fjacd_perms.append((m, n))<EOL>fjacb_perms.append((p, n))<EOL><DEDENT>if m == <NUM_LIT:1>:<EOL><INDENT>fjacd_perms.append((q, n))<EOL><DEDENT>if p == <NUM_LIT:1>:<EOL><INDENT>fjacb_perms.append((q, n))<EOL><DEDENT>if m == q == <NUM_LIT:1>:<EOL><INDENT>fjacd_perms.append((n,))<EOL><DEDENT>if p == q == <NUM_LIT:1>:<EOL><INDENT>fjacb_perms.append((n,))<EOL><DEDENT>arglist = (self.beta0, self.data.x)<EOL>if self.model.extra_args is not None:<EOL><INDENT>arglist = arglist + self.model.extra_args<EOL><DEDENT>res = self.model.fcn(*arglist)<EOL>if res.shape not in fcn_perms:<EOL><INDENT>print(res.shape)<EOL>print(fcn_perms)<EOL>raise odr_error("<STR_LIT>" % y_s)<EOL><DEDENT>if self.model.fjacd is not None:<EOL><INDENT>res = self.model.fjacd(*arglist)<EOL>if res.shape not in fjacd_perms:<EOL><INDENT>raise odr_error(<EOL>"<STR_LIT>" % (q, m, n))<EOL><DEDENT><DEDENT>if self.model.fjacb is not None:<EOL><INDENT>res = self.model.fjacb(*arglist)<EOL>if res.shape not in fjacb_perms:<EOL><INDENT>raise odr_error(<EOL>"<STR_LIT>" % (q, p, n))<EOL><DEDENT><DEDENT>if self.delta0 is not None and self.delta0.shape != self.data.x.shape:<EOL><INDENT>raise odr_error(<EOL>"<STR_LIT>" % self.data.x.shape)<EOL><DEDENT>

Check the inputs for consistency, but don't bother checking things
        that the builtin function odr will check.


if attr in self.meta:<EOL><INDENT>return self.meta[attr]<EOL><DEDENT>else:<EOL><INDENT>raise AttributeError("<STR_LIT>" % attr)<EOL><DEDENT>

Dispatch attribute access to the metadata.


func.__name__ = self.name<EOL>func.__doc__ = getattr(self, '<STR_LIT>', None)<EOL>func.__dict__ = getattr(self, '<STR_LIT>', {})<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>func.__defaults__ = getattr(self, '<STR_LIT>', ())<EOL><DEDENT>else:<EOL><INDENT>func.func_defaults = getattr(self, '<STR_LIT>', ())<EOL><DEDENT>func.__kwdefaults__ = getattr(self, '<STR_LIT>', None)<EOL>callermodule = sys._getframe(<NUM_LIT:3>).f_globals.get('<STR_LIT>', '<STR_LIT:?>')<EOL>func.__module__ = getattr(self, '<STR_LIT>', callermodule)<EOL>func.__dict__.update(kw)<EOL>

Update the signature of func with the data in self


def make(self, src_templ, evaldict=None, addsource=False, **attrs):

src = src_templ % vars(self)  <EOL>evaldict = evaldict or {}<EOL>mo = DEF.match(src)<EOL>if mo is None:<EOL><INDENT>raise SyntaxError('<STR_LIT>' % src)<EOL><DEDENT>name = mo.group(<NUM_LIT:1>)  <EOL>names = set([name] + [arg.strip('<STR_LIT>') for arg in<EOL>self.shortsignature.split('<STR_LIT:U+002C>')])<EOL>for n in names:<EOL><INDENT>if n in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise NameError('<STR_LIT>' % (n, src))<EOL><DEDENT><DEDENT>if not src.endswith('<STR_LIT:\n>'):  <EOL><INDENT>src += '<STR_LIT:\n>'  <EOL><DEDENT>try:<EOL><INDENT>code = compile(src, '<STR_LIT>', '<STR_LIT>')<EOL>exec_(code, evaldict)<EOL><DEDENT>except:<EOL><INDENT>print('<STR_LIT>', file=sys.stderr)<EOL>print(src, file=sys.stderr)<EOL>raise<EOL><DEDENT>func = evaldict[name]<EOL>if addsource:<EOL><INDENT>attrs['<STR_LIT>'] = src<EOL><DEDENT>self.update(func, **attrs)<EOL>return func<EOL>

Make a new function from a given template and update the signature


@classmethod<EOL><INDENT>def create(cls, obj, body, evaldict, defaults=None,<EOL>doc=None, module=None, addsource=True, **attrs):<DEDENT>

if isinstance(obj, str):  <EOL><INDENT>name, rest = obj.strip().split('<STR_LIT:(>', <NUM_LIT:1>)<EOL>signature = rest[:-<NUM_LIT:1>]  <EOL>func = None<EOL><DEDENT>else:  <EOL><INDENT>name = None<EOL>signature = None<EOL>func = obj<EOL><DEDENT>self = cls(func, name, signature, defaults, doc, module)<EOL>ibody = '<STR_LIT:\n>'.join('<STR_LIT:U+0020>' + line for line in body.splitlines())<EOL>return self.make('<STR_LIT>' + ibody,<EOL>evaldict, addsource, **attrs)<EOL>

Create a function from the strings name, signature and body.
evaldict is the evaluation dictionary. If addsource is true an attribute
__source__ is added to the result. The attributes attrs are added,
if any.


orig_state = gc.isenabled()<EOL>set_gc_state(state)<EOL>yield<EOL>set_gc_state(orig_state)<EOL>

Context manager to set state of garbage collector to `state`

    Parameters
    ----------
    state : bool
        True for gc enabled, False for disabled

    Examples
    --------
    >>> with gc_state(False):
    ...     assert not gc.isenabled()
    >>> with gc_state(True):
    ...     assert gc.isenabled()


@contextmanager<EOL>def assert_deallocated(func, *args, **kwargs):

with gc_state(False):<EOL><INDENT>obj = func(*args, **kwargs)<EOL>ref = weakref.ref(obj)<EOL>yield obj<EOL>del obj<EOL>if ref() is not None:<EOL><INDENT>raise ReferenceError("<STR_LIT>")<EOL><DEDENT><DEDENT>

Context manager to check that object is deallocated

    This is useful for checking that an object can be freed directly by
    reference counting, without requiring gc to break reference cycles.
    GC is disabled inside the context manager.

    Parameters
    ----------
    func : callable
        Callable to create object to check
    \*args : sequence
        positional arguments to `func` in order to create object to check
    \*\*kwargs : dict
        keyword arguments to `func` in order to create object to check

    Examples
    --------
    >>> class C(object): pass
    >>> with assert_deallocated(C) as c:
    ...     # do something
    ...     del c

    >>> class C(object):
    ...     def __init__(self):
    ...         self._circular = self # Make circular reference
    >>> with assert_deallocated(C) as c: #doctest: +IGNORE_EXCEPTION_DETAIL
    ...     # do something
    ...     del c
    Traceback (most recent call last):
        ...
    ReferenceError: Remaining reference(s) to object


return iter(getattr(d, _iterkeys)())<EOL>

Return an iterator over the keys of a dictionary.


return iter(getattr(d, _iteritems)())<EOL>

Return an iterator over the (key, value) pairs of a dictionary.


return meta("<STR_LIT>", (base,), {})<EOL>


if self.pre_release == other.pre_release:<EOL><INDENT>vercmp = <NUM_LIT:0><EOL><DEDENT>elif self.pre_release == '<STR_LIT>':<EOL><INDENT>vercmp = <NUM_LIT:1><EOL><DEDENT>elif other.pre_release == '<STR_LIT>':<EOL><INDENT>vercmp = -<NUM_LIT:1><EOL><DEDENT>elif self.pre_release > other.pre_release:<EOL><INDENT>vercmp = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>vercmp = -<NUM_LIT:1><EOL><DEDENT>return vercmp<EOL>


<EOL>force_clapack = <NUM_LIT:0><EOL>ordering = []<EOL>for i in range(len(arrays)):<EOL><INDENT>t = arrays[i].dtype.char<EOL>if t not in _type_conv:<EOL><INDENT>t = '<STR_LIT:d>'<EOL><DEDENT>ordering.append((t,i))<EOL><DEDENT>if ordering:<EOL><INDENT>ordering.sort()<EOL>required_prefix = _type_conv[ordering[<NUM_LIT:0>][<NUM_LIT:0>]]<EOL><DEDENT>else:<EOL><INDENT>required_prefix = '<STR_LIT:d>'<EOL><DEDENT>dtypechar = _inv_type_conv[required_prefix]<EOL>if ordering and arrays[ordering[<NUM_LIT:0>][<NUM_LIT:1>]].flags['<STR_LIT>']:<EOL><INDENT>m1,m2 = flapack,clapack<EOL><DEDENT>else:<EOL><INDENT>m1,m2 = clapack,flapack<EOL><DEDENT>if not _use_force_clapack:<EOL><INDENT>force_clapack = <NUM_LIT:0><EOL><DEDENT>funcs = []<EOL>m1_name = m1.__name__.split('<STR_LIT:.>')[-<NUM_LIT:1>]<EOL>m2_name = m2.__name__.split('<STR_LIT:.>')[-<NUM_LIT:1>]<EOL>for name in names:<EOL><INDENT>func_name = required_prefix + name<EOL>func = getattr(m1,func_name,None)<EOL>if func is None:<EOL><INDENT>func = getattr(m2,func_name)<EOL>func.module_name = m2_name<EOL><DEDENT>else:<EOL><INDENT>func.module_name = m1_name<EOL>if force_clapack and m1 is flapack:<EOL><INDENT>func2 = getattr(m2,func_name,None)<EOL>if func2 is not None:<EOL><INDENT>import new<EOL>func_code = None   <EOL>exec(_colmajor_func_template % {'<STR_LIT>':func_name})<EOL>func = new.function(func_code,{'<STR_LIT>':func2},func_name)<EOL>func.module_name = m2_name<EOL>func.__doc__ = func2.__doc__<EOL><DEDENT><DEDENT><DEDENT>func.prefix = required_prefix<EOL>func.dtypechar = dtypechar<EOL>funcs.append(func)<EOL><DEDENT>return tuple(funcs)<EOL>

Return available LAPACK function objects with names.
    arrays are used to determine the optimal prefix of
    LAPACK routines.
    If force_clapack is True then available Atlas routine
    is returned for column major storaged arrays with
    rowmajor argument set to False.


if copy:<EOL><INDENT>return dia_matrix((data, self.offsets.copy()), shape=self.shape)<EOL><DEDENT>else:<EOL><INDENT>return dia_matrix((data,self.offsets), shape=self.shape)<EOL><DEDENT>

Returns a matrix with the same sparsity structure as self,
        but with different data.  By default the structure arrays are copied.


def validate_graph(csgraph, directed, dtype=DTYPE,<EOL>csr_output=True, dense_output=True,<EOL>copy_if_dense=False, copy_if_sparse=False,<EOL>null_value_in=<NUM_LIT:0>, null_value_out=np.inf,<EOL>infinity_null=True, nan_null=True):

if not (csr_output or dense_output):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (not directed) and isspmatrix_csc(csgraph):<EOL><INDENT>csgraph = csgraph.T<EOL><DEDENT>if isspmatrix(csgraph):<EOL><INDENT>if csr_output:<EOL><INDENT>csgraph = csr_matrix(csgraph, dtype=DTYPE, copy=copy_if_sparse)<EOL><DEDENT>else:<EOL><INDENT>csgraph = csgraph_to_dense(csgraph, null_value=null_value_out)<EOL><DEDENT><DEDENT>elif np.ma.isMaskedArray(csgraph):<EOL><INDENT>if dense_output:<EOL><INDENT>mask = csgraph.mask<EOL>csgraph = np.array(csgraph.data, dtype=DTYPE, copy=copy_if_dense)<EOL>csgraph[mask] = null_value_out<EOL><DEDENT>else:<EOL><INDENT>csgraph = csgraph_from_masked(csgraph)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if dense_output:<EOL><INDENT>csgraph = csgraph_masked_from_dense(csgraph,<EOL>copy=copy_if_dense,<EOL>null_value=null_value_in,<EOL>nan_null=nan_null,<EOL>infinity_null=infinity_null)<EOL>mask = csgraph.mask<EOL>csgraph = np.asarray(csgraph.data, dtype=DTYPE)<EOL>csgraph[mask] = null_value_out<EOL><DEDENT>else:<EOL><INDENT>csgraph = csgraph_from_dense(csgraph, null_value=null_value_in,<EOL>infinity_null=infinity_null,<EOL>nan_null=nan_null)<EOL><DEDENT><DEDENT>if csgraph.ndim != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if csgraph.shape[<NUM_LIT:0>] != csgraph.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return csgraph<EOL>

Routine for validation and conversion of csgraph inputs


def diags(diagonals, offsets, shape=None, format=None, dtype=None):

<EOL>try:<EOL><INDENT>iter(offsets)<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>iter(diagonals[<NUM_LIT:0>])<EOL><DEDENT>except TypeError:<EOL><INDENT>diagonals = [np.atleast_1d(diagonals)]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>diagonals = list(map(np.atleast_1d, diagonals))<EOL><DEDENT>offsets = np.atleast_1d(offsets)<EOL>if len(diagonals) != len(offsets):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if shape is None:<EOL><INDENT>m = len(diagonals[<NUM_LIT:0>]) + abs(int(offsets[<NUM_LIT:0>]))<EOL>shape = (m, m)<EOL><DEDENT>if dtype is None:<EOL><INDENT>dtype = np.common_type(*diagonals)<EOL><DEDENT>m, n = shape<EOL>M = max([min(m + offset, n - offset) + max(<NUM_LIT:0>, offset)<EOL>for offset in offsets])<EOL>M = max(<NUM_LIT:0>, M)<EOL>data_arr = np.zeros((len(offsets), M), dtype=dtype)<EOL>for j, diagonal in enumerate(diagonals):<EOL><INDENT>offset = offsets[j]<EOL>k = max(<NUM_LIT:0>, offset)<EOL>length = min(m + offset, n - offset)<EOL>if length <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" % (offset, j))<EOL><DEDENT>try:<EOL><INDENT>data_arr[j, k:k+length] = diagonal<EOL><DEDENT>except ValueError:<EOL><INDENT>if len(diagonal) != length and len(diagonal) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (<EOL>j, len(diagonal), offset, m, n))<EOL><DEDENT>raise<EOL><DEDENT><DEDENT>return dia_matrix((data_arr, offsets), shape=(m, n)).asformat(format)<EOL>

Construct a sparse matrix from diagonals.

Parameters
----------
diagonals : sequence of array_like
    Sequence of arrays containing the matrix diagonals,
    corresponding to `offsets`.
offsets  : sequence of int
    Diagonals to set:
      - k = 0  the main diagonal
      - k > 0  the k-th upper diagonal
      - k < 0  the k-th lower diagonal
shape : tuple of int, optional
    Shape of the result. If omitted, a square matrix large enough
    to contain the diagonals is returned.
format : {"dia", "csr", "csc", "lil", ...}, optional
    Matrix format of the result.  By default (format=None) an
    appropriate sparse matrix format is returned.  This choice is
    subject to change.
dtype : dtype, optional
    Data type of the matrix.

See Also
--------
spdiags : construct matrix from diagonals

Notes
-----
This function differs from `spdiags` in the way it handles
off-diagonals.

The result from `diags` is the sparse equivalent of::

    np.diag(diagonals[0], offsets[0])
    + ...
    + np.diag(diagonals[k], offsets[k])

Repeated diagonal offsets are disallowed.

.. versionadded:: 0.11

Examples
--------
>>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]]
>>> diags(diagonals, [0, -1, 2]).toarray()
array([[1, 0, 1, 0],
       [1, 2, 0, 2],
       [0, 2, 3, 0],
       [0, 0, 3, 4]])

Broadcasting of scalars is supported (but shape needs to be
specified):

>>> diags([1, -2, 1], [-1, 0, 1], shape=(4, 4)).toarray()
array([[-2.,  1.,  0.,  0.],
       [ 1., -2.,  1.,  0.],
       [ 0.,  1., -2.,  1.],
       [ 0.,  0.,  1., -2.]])

If only one diagonal is wanted (as in `numpy.diag`), the following
works as well:

>>> diags([1, 2, 3], 1).toarray()
array([[ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  2.,  0.],
       [ 0.,  0.,  0.,  3.],
       [ 0.,  0.,  0.,  0.]])


data, indices, indptr = _same_sum_duplicate(M.data, M.indices,<EOL>indptr=M.indptr)<EOL>for start, stop in izip(indptr, indptr[<NUM_LIT:1>:]):<EOL><INDENT>indices[start:stop] = indices[start:stop][::-<NUM_LIT:1>].copy()<EOL>data[start:stop] = data[start:stop][::-<NUM_LIT:1>].copy()<EOL><DEDENT>return data, indices, indptr<EOL>

Return non-canonical constructor arg1 equivalent to M


if require:<EOL><INDENT>return cls<EOL><DEDENT>else:<EOL><INDENT>def wrap(fc):<EOL><INDENT>def wrapper(*a, **kw):<EOL><INDENT>try:<EOL><INDENT>return fc(*a, **kw)<EOL><DEDENT>except (NotImplementedError, TypeError, ValueError,<EOL>IndexError, AttributeError):<EOL><INDENT>raise nose.SkipTest("<STR_LIT>")<EOL><DEDENT><DEDENT>wrapper.__name__ = fc.__name__<EOL>return wrapper<EOL><DEDENT>new_dict = dict(cls.__dict__)<EOL>for name, func in cls.__dict__.items():<EOL><INDENT>if name.startswith('<STR_LIT>'):<EOL><INDENT>new_dict[name] = wrap(func)<EOL><DEDENT><DEDENT>return type(cls.__name__ + "<STR_LIT>",<EOL>cls.__bases__,<EOL>new_dict)<EOL><DEDENT>

Construct a class that either runs tests as usual (require=True),
or each method raises SkipTest if it encounters a common error.


sqrt_m_max = np.sqrt(m_max)<EOL>p_low = int(np.floor(sqrt_m_max))<EOL>p_high = int(np.ceil(sqrt_m_max + <NUM_LIT:1>))<EOL>return max(p for p in range(p_low, p_high+<NUM_LIT:1>) if p*(p-<NUM_LIT:1>) <= m_max + <NUM_LIT:1>)<EOL>

Compute the largest positive integer p such that p*(p-1) <= m_max + 1.

Do this in a slightly dumb way, but safe and not too slow.

Parameters
----------
m_max : int
    A count related to bounds.


def _expm_multiply_interval_core_0(A, X, h, mu, m_star, s, q):

for k in range(q):<EOL><INDENT>X[k+<NUM_LIT:1>] = _expm_multiply_simple_core(A, X[k], h, mu, m_star, s)<EOL><DEDENT>return X, <NUM_LIT:0><EOL>


def expm_multiply(A, B, start=None, stop=None, num=None, endpoint=None):

if all(arg is None for arg in (start, stop, num, endpoint)):<EOL><INDENT>X = _expm_multiply_simple(A, B)<EOL><DEDENT>else:<EOL><INDENT>X, status = _expm_multiply_interval(A, B, start, stop, num, endpoint)<EOL><DEDENT>return X<EOL>

Compute the action of the matrix exponential of A on B.

Parameters
----------
A : transposable linear operator
    The operator whose exponential is of interest.
B : ndarray
    The matrix or vector to be multiplied by the matrix exponential of A.
start : scalar, optional
    The starting time point of the sequence.
stop : scalar, optional
    The end time point of the sequence, unless `endpoint` is set to False.
    In that case, the sequence consists of all but the last of ``num + 1``
    evenly spaced time points, so that `stop` is excluded.
    Note that the step size changes when `endpoint` is False.
num : int, optional
    Number of time points to use.
endpoint : bool, optional
    If True, `stop` is the last time point.  Otherwise, it is not included.

Returns
-------
expm_A_B : ndarray
     The result of the action :math:`e^{t_k A} B`.

Notes
-----
The optional arguments defining the sequence of evenly spaced time points
are compatible with the arguments of `numpy.linspace`.

The output ndarray shape is somewhat complicated so I explain it here.
The ndim of the output could be either 1, 2, or 3.
It would be 1 if you are computing the expm action on a single vector
at a single time point.
It would be 2 if you are computing the expm action on a vector
at multiple time points, or if you are computing the expm action
on a matrix at a single time point.
It would be 3 if you want the action on a matrix with multiple
columns at multiple time points.
If multiple time points are requested, expm_A_B[0] will always
be the action of the expm at the first time point,
regardless of whether the action is on a vector or a matrix.

References
----------
.. [1] Awad H. Al-Mohy and Nicholas J. Higham (2011)
       "Computing the Action of the Matrix Exponential,
       with an Application to Exponential Integrators."
       SIAM Journal on Scientific Computing,
       33 (2). pp. 488-511. ISSN 1064-8275
       http://eprints.ma.man.ac.uk/1591/

.. [2] Nicholas J. Higham and Awad H. Al-Mohy (2010)
       "Computing Matrix Functions."
       Acta Numerica,
       19. 159-208. ISSN 0962-4929
       http://eprints.ma.man.ac.uk/1451/


if p not in self._d:<EOL><INDENT>est = _onenormest_matrix_power(self._A, p, self._ell)<EOL>self._d[p] = est ** (<NUM_LIT:1.0> / p)<EOL><DEDENT>return self._d[p]<EOL>

Lazily estimate d_p(A) ~= || A^p ||^(1/p) where ||.|| is the 1-norm.


def _condition_3_13(A_1_norm, n0, m_max, ell):

<EOL>p_max = _compute_p_max(m_max)<EOL>a = <NUM_LIT:2> * ell * p_max * (p_max + <NUM_LIT:3>)<EOL>b = _theta[m_max] / float(n0 * m_max)<EOL>return A_1_norm <= a * b<EOL>

A helper function for the _expm_multiply_* functions.

Parameters
----------
A_1_norm : float
    The precomputed 1-norm of A.
n0 : int
    Number of columns in the _expm_multiply_* B matrix.
m_max : int
    A value related to a bound.
ell : int
    The number of columns used in the 1-norm approximation.
    This is usually taken to be small, maybe between 1 and 5.

Returns
-------
value : bool
    Indicates whether or not the condition has been met.

Notes
-----
This is condition (3.13) in Al-Mohy and Higham (2011).


<EOL>if n != int(n) or n < <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>n = int(n)<EOL>if p != int(p) or p < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>p = int(p)<EOL>a, b = divmod(p, n)<EOL>large = np.power(<NUM_LIT>, -n*a)<EOL>small = large * np.power(<NUM_LIT>, -n)<EOL>return np.diag([large]*(n-b), b) + np.diag([small]*b, b-n)<EOL>

A helper function for testing matrix functions.

Parameters
----------
n : integer greater than 1
    Order of the square matrix to be returned.
p : non-negative integer
    Power of the matrix.

Returns
-------
out : ndarray representing a square matrix
    A Forsythe matrix of order n, raised to the power p.


def lsqr(A, b, damp=<NUM_LIT:0.0>, atol=<NUM_LIT>, btol=<NUM_LIT>, conlim=<NUM_LIT>,<EOL>iter_lim=None, show=False, calc_var=False):

A = aslinearoperator(A)<EOL>if len(b.shape) > <NUM_LIT:1>:<EOL><INDENT>b = b.squeeze()<EOL><DEDENT>m, n = A.shape<EOL>if iter_lim is None:<EOL><INDENT>iter_lim = <NUM_LIT:2> * n<EOL><DEDENT>var = np.zeros(n)<EOL>msg = ('<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>')<EOL>if show:<EOL><INDENT>print('<STR_LIT:U+0020>')<EOL>print('<STR_LIT>')<EOL>str1 = '<STR_LIT>' % (m, n)<EOL>str2 = '<STR_LIT>' % (damp, calc_var)<EOL>str3 = '<STR_LIT>' % (atol, conlim)<EOL>str4 = '<STR_LIT>' % (btol, iter_lim)<EOL>print(str1)<EOL>print(str2)<EOL>print(str3)<EOL>print(str4)<EOL><DEDENT>itn = <NUM_LIT:0><EOL>istop = <NUM_LIT:0><EOL>nstop = <NUM_LIT:0><EOL>ctol = <NUM_LIT:0><EOL>if conlim > <NUM_LIT:0>:<EOL><INDENT>ctol = <NUM_LIT:1>/conlim<EOL><DEDENT>anorm = <NUM_LIT:0><EOL>acond = <NUM_LIT:0><EOL>dampsq = damp**<NUM_LIT:2><EOL>ddnorm = <NUM_LIT:0><EOL>res2 = <NUM_LIT:0><EOL>xnorm = <NUM_LIT:0><EOL>xxnorm = <NUM_LIT:0><EOL>z = <NUM_LIT:0><EOL>cs2 = -<NUM_LIT:1><EOL>sn2 = <NUM_LIT:0><EOL>"""<STR_LIT>"""<EOL>__xm = np.zeros(m)  <EOL>__xn = np.zeros(n)  <EOL>v = np.zeros(n)<EOL>u = b<EOL>x = np.zeros(n)<EOL>alfa = <NUM_LIT:0><EOL>beta = np.linalg.norm(u)<EOL>w = np.zeros(n)<EOL>if beta > <NUM_LIT:0>:<EOL><INDENT>u = (<NUM_LIT:1>/beta) * u<EOL>v = A.rmatvec(u)<EOL>alfa = np.linalg.norm(v)<EOL><DEDENT>if alfa > <NUM_LIT:0>:<EOL><INDENT>v = (<NUM_LIT:1>/alfa) * v<EOL>w = v.copy()<EOL><DEDENT>rhobar = alfa<EOL>phibar = beta<EOL>bnorm = beta<EOL>rnorm = beta<EOL>r1norm = rnorm<EOL>r2norm = rnorm<EOL>arnorm = alfa * beta<EOL>if arnorm == <NUM_LIT:0>:<EOL><INDENT>print(msg[<NUM_LIT:0>])<EOL>return x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var<EOL><DEDENT>head1 = '<STR_LIT>'<EOL>head2 = '<STR_LIT>'<EOL>if show:<EOL><INDENT>print('<STR_LIT:U+0020>')<EOL>print(head1, head2)<EOL>test1 = <NUM_LIT:1><EOL>test2 = alfa / beta<EOL>str1 = '<STR_LIT>' % (itn, x[<NUM_LIT:0>])<EOL>str2 = '<STR_LIT>' % (r1norm, r2norm)<EOL>str3 = '<STR_LIT>' % (test1, test2)<EOL>print(str1, str2, str3)<EOL><DEDENT>while itn < iter_lim:<EOL><INDENT>itn = itn + <NUM_LIT:1><EOL>"""<STR_LIT>"""<EOL>u = A.matvec(v) - alfa * u<EOL>beta = np.linalg.norm(u)<EOL>if beta > <NUM_LIT:0>:<EOL><INDENT>u = (<NUM_LIT:1>/beta) * u<EOL>anorm = sqrt(anorm**<NUM_LIT:2> + alfa**<NUM_LIT:2> + beta**<NUM_LIT:2> + damp**<NUM_LIT:2>)<EOL>v = A.rmatvec(u) - beta * v<EOL>alfa = np.linalg.norm(v)<EOL>if alfa > <NUM_LIT:0>:<EOL><INDENT>v = (<NUM_LIT:1> / alfa) * v<EOL><DEDENT><DEDENT>rhobar1 = sqrt(rhobar**<NUM_LIT:2> + damp**<NUM_LIT:2>)<EOL>cs1 = rhobar / rhobar1<EOL>sn1 = damp / rhobar1<EOL>psi = sn1 * phibar<EOL>phibar = cs1 * phibar<EOL>cs, sn, rho = _sym_ortho(rhobar1, beta)<EOL>theta = sn * alfa<EOL>rhobar = -cs * alfa<EOL>phi = cs * phibar<EOL>phibar = sn * phibar<EOL>tau = sn * phi<EOL>t1 = phi / rho<EOL>t2 = -theta / rho<EOL>dk = (<NUM_LIT:1> / rho) * w<EOL>x = x + t1 * w<EOL>w = v + t2 * w<EOL>ddnorm = ddnorm + np.linalg.norm(dk)**<NUM_LIT:2><EOL>if calc_var:<EOL><INDENT>var = var + dk**<NUM_LIT:2><EOL><DEDENT>delta = sn2 * rho<EOL>gambar = -cs2 * rho<EOL>rhs = phi - delta * z<EOL>zbar = rhs / gambar<EOL>xnorm = sqrt(xxnorm + zbar**<NUM_LIT:2>)<EOL>gamma = sqrt(gambar**<NUM_LIT:2> + theta**<NUM_LIT:2>)<EOL>cs2 = gambar / gamma<EOL>sn2 = theta / gamma<EOL>z = rhs / gamma<EOL>xxnorm = xxnorm + z**<NUM_LIT:2><EOL>acond = anorm * sqrt(ddnorm)<EOL>res1 = phibar**<NUM_LIT:2><EOL>res2 = res2 + psi**<NUM_LIT:2><EOL>rnorm = sqrt(res1 + res2)<EOL>arnorm = alfa * abs(tau)<EOL>r1sq = rnorm**<NUM_LIT:2> - dampsq * xxnorm<EOL>r1norm = sqrt(abs(r1sq))<EOL>if r1sq < <NUM_LIT:0>:<EOL><INDENT>r1norm = -r1norm<EOL><DEDENT>r2norm = rnorm<EOL>test1 = rnorm / bnorm<EOL>test2 = arnorm / (anorm * rnorm + eps)<EOL>test3 = <NUM_LIT:1> / (acond + eps)<EOL>t1 = test1 / (<NUM_LIT:1> + anorm * xnorm / bnorm)<EOL>rtol = btol + atol * anorm * xnorm / bnorm<EOL>if itn >= iter_lim:<EOL><INDENT>istop = <NUM_LIT:7><EOL><DEDENT>if <NUM_LIT:1> + test3 <= <NUM_LIT:1>:<EOL><INDENT>istop = <NUM_LIT:6><EOL><DEDENT>if <NUM_LIT:1> + test2 <= <NUM_LIT:1>:<EOL><INDENT>istop = <NUM_LIT:5><EOL><DEDENT>if <NUM_LIT:1> + t1 <= <NUM_LIT:1>:<EOL><INDENT>istop = <NUM_LIT:4><EOL><DEDENT>if test3 <= ctol:<EOL><INDENT>istop = <NUM_LIT:3><EOL><DEDENT>if test2 <= atol:<EOL><INDENT>istop = <NUM_LIT:2><EOL><DEDENT>if test1 <= rtol:<EOL><INDENT>istop = <NUM_LIT:1><EOL><DEDENT>prnt = False<EOL>if n <= <NUM_LIT>:<EOL><INDENT>prnt = True<EOL><DEDENT>if itn <= <NUM_LIT:10>:<EOL><INDENT>prnt = True<EOL><DEDENT>if itn >= iter_lim-<NUM_LIT:10>:<EOL><INDENT>prnt = True<EOL><DEDENT>if test3 <= <NUM_LIT:2>*ctol:<EOL><INDENT>prnt = True<EOL><DEDENT>if test2 <= <NUM_LIT:10>*atol:<EOL><INDENT>prnt = True<EOL><DEDENT>if test1 <= <NUM_LIT:10>*rtol:<EOL><INDENT>prnt = True<EOL><DEDENT>if istop != <NUM_LIT:0>:<EOL><INDENT>prnt = True<EOL><DEDENT>if prnt:<EOL><INDENT>if show:<EOL><INDENT>str1 = '<STR_LIT>' % (itn, x[<NUM_LIT:0>])<EOL>str2 = '<STR_LIT>' % (r1norm, r2norm)<EOL>str3 = '<STR_LIT>' % (test1, test2)<EOL>str4 = '<STR_LIT>' % (anorm, acond)<EOL>print(str1, str2, str3, str4)<EOL><DEDENT><DEDENT>if istop != <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if show:<EOL><INDENT>print('<STR_LIT:U+0020>')<EOL>print('<STR_LIT>')<EOL>print(msg[istop])<EOL>print('<STR_LIT:U+0020>')<EOL>str1 = '<STR_LIT>' % (istop, r1norm)<EOL>str2 = '<STR_LIT>' % (anorm, arnorm)<EOL>str3 = '<STR_LIT>' % (itn, r2norm)<EOL>str4 = '<STR_LIT>' % (acond, xnorm)<EOL>print(str1 + '<STR_LIT:U+0020>' + str2)<EOL>print(str3 + '<STR_LIT:U+0020>' + str4)<EOL>print('<STR_LIT:U+0020>')<EOL><DEDENT>return x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var<EOL>

Find the least-squares solution to a large, sparse, linear system
    of equations.

    The function solves ``Ax = b``  or  ``min ||b - Ax||^2`` or
    ``min ||Ax - b||^2 + d^2 ||x||^2``.

    The matrix A may be square or rectangular (over-determined or
    under-determined), and may have any rank.

    ::

      1. Unsymmetric equations --    solve  A*x = b

      2. Linear least squares  --    solve  A*x = b
                                     in the least-squares sense

      3. Damped least squares  --    solve  (   A    )*x = ( b )
                                            ( damp*I )     ( 0 )
                                     in the least-squares sense

    Parameters
    ----------
    A : {sparse matrix, ndarray, LinearOperator}
        Representation of an m-by-n matrix.  It is required that
        the linear operator can produce ``Ax`` and ``A^T x``.
    b : (m,) ndarray
        Right-hand side vector ``b``.
    damp : float
        Damping coefficient.
    atol, btol : float
        Stopping tolerances. If both are 1.0e-9 (say), the final
        residual norm should be accurate to about 9 digits.  (The
        final x will usually have fewer correct digits, depending on
        cond(A) and the size of damp.)
    conlim : float
        Another stopping tolerance.  lsqr terminates if an estimate of
        ``cond(A)`` exceeds `conlim`.  For compatible systems ``Ax =
        b``, `conlim` could be as large as 1.0e+12 (say).  For
        least-squares problems, conlim should be less than 1.0e+8.
        Maximum precision can be obtained by setting ``atol = btol =
        conlim = zero``, but the number of iterations may then be
        excessive.
    iter_lim : int
        Explicit limitation on number of iterations (for safety).
    show : bool
        Display an iteration log.
    calc_var : bool
        Whether to estimate diagonals of ``(A'A + damp^2*I)^{-1}``.

    Returns
    -------
    x : ndarray of float
        The final solution.
    istop : int
        Gives the reason for termination.
        1 means x is an approximate solution to Ax = b.
        2 means x approximately solves the least-squares problem.
    itn : int
        Iteration number upon termination.
    r1norm : float
        ``norm(r)``, where ``r = b - Ax``.
    r2norm : float
        ``sqrt( norm(r)^2  +  damp^2 * norm(x)^2 )``.  Equal to `r1norm` if
        ``damp == 0``.
    anorm : float
        Estimate of Frobenius norm of ``Abar = [[A]; [damp*I]]``.
    acond : float
        Estimate of ``cond(Abar)``.
    arnorm : float
        Estimate of ``norm(A'*r - damp^2*x)``.
    xnorm : float
        ``norm(x)``
    var : ndarray of float
        If ``calc_var`` is True, estimates all diagonals of
        ``(A'A)^{-1}`` (if ``damp == 0``) or more generally ``(A'A +
        damp^2*I)^{-1}``.  This is well defined if A has full column
        rank or ``damp > 0``.  (Not sure what var means if ``rank(A)
        < n`` and ``damp = 0.``)

    Notes
    -----
    LSQR uses an iterative method to approximate the solution.  The
    number of iterations required to reach a certain accuracy depends
    strongly on the scaling of the problem.  Poor scaling of the rows
    or columns of A should therefore be avoided where possible.

    For example, in problem 1 the solution is unaltered by
    row-scaling.  If a row of A is very small or large compared to
    the other rows of A, the corresponding row of ( A  b ) should be
    scaled up or down.

    In problems 1 and 2, the solution x is easily recovered
    following column-scaling.  Unless better information is known,
    the nonzero columns of A should be scaled so that they all have
    the same Euclidean norm (e.g., 1.0).

    In problem 3, there is no freedom to re-scale if damp is
    nonzero.  However, the value of damp should be assigned only
    after attention has been paid to the scaling of A.

    The parameter damp is intended to help regularize
    ill-conditioned systems, by preventing the true solution from
    being very large.  Another aid to regularization is provided by
    the parameter acond, which may be used to terminate iterations
    before the computed solution becomes very large.

    If some initial estimate ``x0`` is known and if ``damp == 0``,
    one could proceed as follows:

      1. Compute a residual vector ``r0 = b - A*x0``.
      2. Use LSQR to solve the system  ``A*dx = r0``.
      3. Add the correction dx to obtain a final solution ``x = x0 + dx``.

    This requires that ``x0`` be available before and after the call
    to LSQR.  To judge the benefits, suppose LSQR takes k1 iterations
    to solve A*x = b and k2 iterations to solve A*dx = r0.
    If x0 is "good", norm(r0) will be smaller than norm(b).
    If the same stopping tolerances atol and btol are used for each
    system, k1 and k2 will be similar, but the final solution x0 + dx
    should be more accurate.  The only way to reduce the total work
    is to use a larger stopping tolerance for the second system.
    If some value btol is suitable for A*x = b, the larger value
    btol*norm(b)/norm(r0)  should be suitable for A*dx = r0.

    Preconditioning is another way to reduce the number of iterations.
    If it is possible to solve a related system ``M*x = b``
    efficiently, where M approximates A in some helpful way (e.g. M -
    A has low rank or its elements are small relative to those of A),
    LSQR may converge more rapidly on the system ``A*M(inverse)*z =
    b``, after which x can be recovered by solving M*x = z.

    If A is symmetric, LSQR should not be used!

    Alternatives are the symmetric conjugate-gradient method (cg)
    and/or SYMMLQ.  SYMMLQ is an implementation of symmetric cg that
    applies to any symmetric A and will converge more rapidly than
    LSQR.  If A is positive definite, there are other implementations
    of symmetric cg that require slightly less work per iteration than
    SYMMLQ (but will take the same number of iterations).

    References
    ----------
    .. [1] C. C. Paige and M. A. Saunders (1982a).
           "LSQR: An algorithm for sparse linear equations and
           sparse least squares", ACM TOMS 8(1), 43-71.
    .. [2] C. C. Paige and M. A. Saunders (1982b).
           "Algorithm 583.  LSQR: Sparse linear equations and least
           squares problems", ACM TOMS 8(2), 195-209.
    .. [3] M. A. Saunders (1995).  "Solution of sparse rectangular
           systems using LSQR and CRAIG", BIT 35, 588-604.


def lgmres(A, b, x0=None, tol=<NUM_LIT>, maxiter=<NUM_LIT:1000>, M=None, callback=None,<EOL>inner_m=<NUM_LIT:30>, outer_k=<NUM_LIT:3>, outer_v=None, store_outer_Av=True):

from scipy.linalg.basic import lstsq<EOL>A,M,x,b,postprocess = make_system(A,M,x0,b)<EOL>if not np.isfinite(b).all():<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>matvec = A.matvec<EOL>psolve = M.matvec<EOL>if outer_v is None:<EOL><INDENT>outer_v = []<EOL><DEDENT>axpy, dot, scal = None, None, None<EOL>b_norm = norm2(b)<EOL>if b_norm == <NUM_LIT:0>:<EOL><INDENT>b_norm = <NUM_LIT:1><EOL><DEDENT>for k_outer in xrange(maxiter):<EOL><INDENT>r_outer = matvec(x) - b<EOL>if callback is not None:<EOL><INDENT>callback(x)<EOL><DEDENT>if axpy is None:<EOL><INDENT>if np.iscomplexobj(r_outer) and not np.iscomplexobj(x):<EOL><INDENT>x = x.astype(r_outer.dtype)<EOL><DEDENT>axpy, dot, scal = get_blas_funcs(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>(x, r_outer))<EOL><DEDENT>r_norm = norm2(r_outer)<EOL>if r_norm < tol * b_norm or r_norm < tol:<EOL><INDENT>break<EOL><DEDENT>vs0 = -psolve(r_outer)<EOL>inner_res_0 = norm2(vs0)<EOL>if inner_res_0 == <NUM_LIT:0>:<EOL><INDENT>rnorm = norm2(r_outer)<EOL>raise RuntimeError("<STR_LIT>"<EOL>"<STR_LIT>" % rnorm)<EOL><DEDENT>vs0 = scal(<NUM_LIT:1.0>/inner_res_0, vs0)<EOL>hs = []<EOL>vs = [vs0]<EOL>ws = []<EOL>y = None<EOL>for j in xrange(<NUM_LIT:1>, <NUM_LIT:1> + inner_m + len(outer_v)):<EOL><INDENT>v_new = None<EOL>if j < len(outer_v) + <NUM_LIT:1>:<EOL><INDENT>z, v_new = outer_v[j-<NUM_LIT:1>]<EOL><DEDENT>elif j == len(outer_v) + <NUM_LIT:1>:<EOL><INDENT>z = vs0<EOL><DEDENT>else:<EOL><INDENT>z = vs[-<NUM_LIT:1>]<EOL><DEDENT>if v_new is None:<EOL><INDENT>v_new = psolve(matvec(z))<EOL><DEDENT>else:<EOL><INDENT>v_new = v_new.copy()<EOL><DEDENT>hcur = []<EOL>for v in vs:<EOL><INDENT>alpha = dot(v, v_new)<EOL>hcur.append(alpha)<EOL>v_new = axpy(v, v_new, v.shape[<NUM_LIT:0>], -alpha)  <EOL><DEDENT>hcur.append(norm2(v_new))<EOL>if hcur[-<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>bailout = True<EOL><DEDENT>else:<EOL><INDENT>bailout = False<EOL>v_new = scal(<NUM_LIT:1.0>/hcur[-<NUM_LIT:1>], v_new)<EOL><DEDENT>vs.append(v_new)<EOL>hs.append(hcur)<EOL>ws.append(z)<EOL>if not bailout and j % <NUM_LIT:5> != <NUM_LIT:1> and j < inner_m + len(outer_v) - <NUM_LIT:1>:<EOL><INDENT>continue<EOL><DEDENT>hess = np.zeros((j+<NUM_LIT:1>, j), x.dtype)<EOL>e1 = np.zeros((j+<NUM_LIT:1>,), x.dtype)<EOL>e1[<NUM_LIT:0>] = inner_res_0<EOL>for q in xrange(j):<EOL><INDENT>hess[:(q+<NUM_LIT:2>),q] = hs[q]<EOL><DEDENT>y, resids, rank, s = lstsq(hess, e1)<EOL>inner_res = norm2(np.dot(hess, y) - e1)<EOL>if inner_res < tol * inner_res_0:<EOL><INDENT>break<EOL><DEDENT><DEDENT>dx = ws[<NUM_LIT:0>]*y[<NUM_LIT:0>]<EOL>for w, yc in zip(ws[<NUM_LIT:1>:], y[<NUM_LIT:1>:]):<EOL><INDENT>dx = axpy(w, dx, dx.shape[<NUM_LIT:0>], yc)  <EOL><DEDENT>nx = norm2(dx)<EOL>if store_outer_Av:<EOL><INDENT>q = np.dot(hess, y)<EOL>ax = vs[<NUM_LIT:0>]*q[<NUM_LIT:0>]<EOL>for v, qc in zip(vs[<NUM_LIT:1>:], q[<NUM_LIT:1>:]):<EOL><INDENT>ax = axpy(v, ax, ax.shape[<NUM_LIT:0>], qc)<EOL><DEDENT>outer_v.append((dx/nx, ax/nx))<EOL><DEDENT>else:<EOL><INDENT>outer_v.append((dx/nx, None))<EOL><DEDENT>while len(outer_v) > outer_k:<EOL><INDENT>del outer_v[<NUM_LIT:0>]<EOL><DEDENT>x += dx<EOL><DEDENT>else:<EOL><INDENT>return postprocess(x), maxiter<EOL><DEDENT>return postprocess(x), <NUM_LIT:0><EOL>

Solve a matrix equation using the LGMRES algorithm.

The LGMRES algorithm [BJM]_ [BPh]_ is designed to avoid some problems
in the convergence in restarted GMRES, and often converges in fewer
iterations.

Parameters
----------
A : {sparse matrix, dense matrix, LinearOperator}
    The real or complex N-by-N matrix of the linear system.
b : {array, matrix}
    Right hand side of the linear system. Has shape (N,) or (N,1).
x0  : {array, matrix}
    Starting guess for the solution.
tol : float
    Tolerance to achieve. The algorithm terminates when either the relative
    or the absolute residual is below `tol`.
maxiter : int
    Maximum number of iterations.  Iteration will stop after maxiter
    steps even if the specified tolerance has not been achieved.
M : {sparse matrix, dense matrix, LinearOperator}
    Preconditioner for A.  The preconditioner should approximate the
    inverse of A.  Effective preconditioning dramatically improves the
    rate of convergence, which implies that fewer iterations are needed
    to reach a given error tolerance.
callback : function
    User-supplied function to call after each iteration.  It is called
    as callback(xk), where xk is the current solution vector.
inner_m : int, optional
    Number of inner GMRES iterations per each outer iteration.
outer_k : int, optional
    Number of vectors to carry between inner GMRES iterations.
    According to [BJM]_, good values are in the range of 1...3.
    However, note that if you want to use the additional vectors to
    accelerate solving multiple similar problems, larger values may
    be beneficial.
outer_v : list of tuples, optional
    List containing tuples ``(v, Av)`` of vectors and corresponding
    matrix-vector products, used to augment the Krylov subspace, and
    carried between inner GMRES iterations. The element ``Av`` can
    be `None` if the matrix-vector product should be re-evaluated.
    This parameter is modified in-place by `lgmres`, and can be used
    to pass "guess" vectors in and out of the algorithm when solving
    similar problems.
store_outer_Av : bool, optional
    Whether LGMRES should store also A*v in addition to vectors `v`
    in the `outer_v` list. Default is True.

Returns
-------
x : array or matrix
    The converged solution.
info : int
    Provides convergence information:

        - 0  : successful exit
        - >0 : convergence to tolerance not achieved, number of iterations
        - <0 : illegal input or breakdown

Notes
-----
The LGMRES algorithm [BJM]_ [BPh]_ is designed to avoid the
slowing of convergence in restarted GMRES, due to alternating
residual vectors. Typically, it often outperforms GMRES(m) of
comparable memory requirements by some measure, or at least is not
much worse.

Another advantage in this algorithm is that you can supply it with
'guess' vectors in the `outer_v` argument that augment the Krylov
subspace. If the solution lies close to the span of these vectors,
the algorithm converges faster. This can be useful if several very
similar matrices need to be inverted one after another, such as in
Newton-Krylov iteration where the Jacobian matrix often changes
little in the nonlinear steps.

References
----------
.. [BJM] A.H. Baker and E.R. Jessup and T. Manteuffel,
         SIAM J. Matrix Anal. Appl. 26, 962 (2005).
.. [BPh] A.H. Baker, PhD thesis, University of Colorado (2003).
         http://amath.colorado.edu/activities/thesis/allisonb/Thesis.ps


def lsmr(A, b, damp=<NUM_LIT:0.0>, atol=<NUM_LIT>, btol=<NUM_LIT>, conlim=<NUM_LIT>,<EOL>maxiter=None, show=False):

A = aslinearoperator(A)<EOL>b = b.squeeze()<EOL>msg = ('<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>')<EOL>hdg1 = '<STR_LIT>''<STR_LIT:r>'<EOL>hdg2 = '<STR_LIT>'<EOL>pfreq = <NUM_LIT:20>   <EOL>pcount = <NUM_LIT:0>   <EOL>m, n = A.shape<EOL>minDim = min([m, n])<EOL>if maxiter is None:<EOL><INDENT>maxiter = minDim<EOL><DEDENT>if show:<EOL><INDENT>print('<STR_LIT:U+0020>')<EOL>print('<STR_LIT>')<EOL>print('<STR_LIT>' % (m, n))<EOL>print('<STR_LIT>' % (damp))<EOL>print('<STR_LIT>' % (atol, conlim))<EOL>print('<STR_LIT>' % (btol, maxiter))<EOL><DEDENT>u = b<EOL>beta = norm(u)<EOL>v = zeros(n)<EOL>alpha = <NUM_LIT:0><EOL>if beta > <NUM_LIT:0>:<EOL><INDENT>u = (<NUM_LIT:1> / beta) * u<EOL>v = A.rmatvec(u)<EOL>alpha = norm(v)<EOL><DEDENT>if alpha > <NUM_LIT:0>:<EOL><INDENT>v = (<NUM_LIT:1> / alpha) * v<EOL><DEDENT>itn = <NUM_LIT:0><EOL>zetabar = alpha * beta<EOL>alphabar = alpha<EOL>rho = <NUM_LIT:1><EOL>rhobar = <NUM_LIT:1><EOL>cbar = <NUM_LIT:1><EOL>sbar = <NUM_LIT:0><EOL>h = v.copy()<EOL>hbar = zeros(n)<EOL>x = zeros(n)<EOL>betadd = beta<EOL>betad = <NUM_LIT:0><EOL>rhodold = <NUM_LIT:1><EOL>tautildeold = <NUM_LIT:0><EOL>thetatilde = <NUM_LIT:0><EOL>zeta = <NUM_LIT:0><EOL>d = <NUM_LIT:0><EOL>normA2 = alpha * alpha<EOL>maxrbar = <NUM_LIT:0><EOL>minrbar = <NUM_LIT><EOL>normA = sqrt(normA2)<EOL>condA = <NUM_LIT:1><EOL>normx = <NUM_LIT:0><EOL>normb = beta<EOL>istop = <NUM_LIT:0><EOL>ctol = <NUM_LIT:0><EOL>if conlim > <NUM_LIT:0>:<EOL><INDENT>ctol = <NUM_LIT:1> / conlim<EOL><DEDENT>normr = beta<EOL>normar = alpha * beta<EOL>if normar == <NUM_LIT:0>:<EOL><INDENT>if show:<EOL><INDENT>print(msg[<NUM_LIT:0>])<EOL><DEDENT>return x, istop, itn, normr, normar, normA, condA, normx<EOL><DEDENT>if show:<EOL><INDENT>print('<STR_LIT:U+0020>')<EOL>print(hdg1, hdg2)<EOL>test1 = <NUM_LIT:1><EOL>test2 = alpha / beta<EOL>str1 = '<STR_LIT>' % (itn, x[<NUM_LIT:0>])<EOL>str2 = '<STR_LIT>' % (normr, normar)<EOL>str3 = '<STR_LIT>' % (test1, test2)<EOL>print('<STR_LIT>'.join([str1, str2, str3]))<EOL><DEDENT>while itn < maxiter:<EOL><INDENT>itn = itn + <NUM_LIT:1><EOL>u = A.matvec(v) - alpha * u<EOL>beta = norm(u)<EOL>if beta > <NUM_LIT:0>:<EOL><INDENT>u = (<NUM_LIT:1> / beta) * u<EOL>v = A.rmatvec(u) - beta * v<EOL>alpha = norm(v)<EOL>if alpha > <NUM_LIT:0>:<EOL><INDENT>v = (<NUM_LIT:1> / alpha) * v<EOL><DEDENT><DEDENT>chat, shat, alphahat = _sym_ortho(alphabar, damp)<EOL>rhoold = rho<EOL>c, s, rho = _sym_ortho(alphahat, beta)<EOL>thetanew = s*alpha<EOL>alphabar = c*alpha<EOL>rhobarold = rhobar<EOL>zetaold = zeta<EOL>thetabar = sbar * rho<EOL>rhotemp = cbar * rho<EOL>cbar, sbar, rhobar = _sym_ortho(cbar * rho, thetanew)<EOL>zeta = cbar * zetabar<EOL>zetabar = - sbar * zetabar<EOL>hbar = h - (thetabar * rho / (rhoold * rhobarold)) * hbar<EOL>x = x + (zeta / (rho * rhobar)) * hbar<EOL>h = v - (thetanew / rho) * h<EOL>betaacute = chat * betadd<EOL>betacheck = -shat * betadd<EOL>betahat = c * betaacute<EOL>betadd = -s * betaacute<EOL>thetatildeold = thetatilde<EOL>ctildeold, stildeold, rhotildeold = _sym_ortho(rhodold, thetabar)<EOL>thetatilde = stildeold * rhobar<EOL>rhodold = ctildeold * rhobar<EOL>betad = - stildeold * betad + ctildeold * betahat<EOL>tautildeold = (zetaold - thetatildeold * tautildeold) / rhotildeold<EOL>taud = (zeta - thetatilde * tautildeold) / rhodold<EOL>d = d + betacheck * betacheck<EOL>normr = sqrt(d + (betad - taud)**<NUM_LIT:2> + betadd * betadd)<EOL>normA2 = normA2 + beta * beta<EOL>normA = sqrt(normA2)<EOL>normA2 = normA2 + alpha * alpha<EOL>maxrbar = max(maxrbar, rhobarold)<EOL>if itn > <NUM_LIT:1>:<EOL><INDENT>minrbar = min(minrbar, rhobarold)<EOL><DEDENT>condA = max(maxrbar, rhotemp) / min(minrbar, rhotemp)<EOL>normar = abs(zetabar)<EOL>normx = norm(x)<EOL>test1 = normr / normb<EOL>if (normA * normr) != <NUM_LIT:0>:<EOL><INDENT>test2 = normar / (normA * normr)<EOL><DEDENT>else:<EOL><INDENT>test2 = infty<EOL><DEDENT>test3 = <NUM_LIT:1> / condA<EOL>t1 = test1 / (<NUM_LIT:1> + normA * normx / normb)<EOL>rtol = btol + atol * normA * normx / normb<EOL>if itn >= maxiter:<EOL><INDENT>istop = <NUM_LIT:7><EOL><DEDENT>if <NUM_LIT:1> + test3 <= <NUM_LIT:1>:<EOL><INDENT>istop = <NUM_LIT:6><EOL><DEDENT>if <NUM_LIT:1> + test2 <= <NUM_LIT:1>:<EOL><INDENT>istop = <NUM_LIT:5><EOL><DEDENT>if <NUM_LIT:1> + t1 <= <NUM_LIT:1>:<EOL><INDENT>istop = <NUM_LIT:4><EOL><DEDENT>if test3 <= ctol:<EOL><INDENT>istop = <NUM_LIT:3><EOL><DEDENT>if test2 <= atol:<EOL><INDENT>istop = <NUM_LIT:2><EOL><DEDENT>if test1 <= rtol:<EOL><INDENT>istop = <NUM_LIT:1><EOL><DEDENT>if show:<EOL><INDENT>if (n <= <NUM_LIT>) or (itn <= <NUM_LIT:10>) or (itn >= maxiter - <NUM_LIT:10>) or(itn % <NUM_LIT:10> == <NUM_LIT:0>) or (test3 <= <NUM_LIT> * ctol) or(test2 <= <NUM_LIT> * atol) or (test1 <= <NUM_LIT> * rtol) or(istop != <NUM_LIT:0>):<EOL><INDENT>if pcount >= pfreq:<EOL><INDENT>pcount = <NUM_LIT:0><EOL>print('<STR_LIT:U+0020>')<EOL>print(hdg1, hdg2)<EOL><DEDENT>pcount = pcount + <NUM_LIT:1><EOL>str1 = '<STR_LIT>' % (itn, x[<NUM_LIT:0>])<EOL>str2 = '<STR_LIT>' % (normr, normar)<EOL>str3 = '<STR_LIT>' % (test1, test2)<EOL>str4 = '<STR_LIT>' % (normA, condA)<EOL>print('<STR_LIT>'.join([str1, str2, str3, str4]))<EOL><DEDENT><DEDENT>if istop > <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if show:<EOL><INDENT>print('<STR_LIT:U+0020>')<EOL>print('<STR_LIT>')<EOL>print(msg[istop])<EOL>print('<STR_LIT>' % (istop, normr))<EOL>print('<STR_LIT>' % (normA, normar))<EOL>print('<STR_LIT>' % (itn, condA))<EOL>print('<STR_LIT>' % (normx))<EOL>print(str1, str2)<EOL>print(str3, str4)<EOL><DEDENT>return x, istop, itn, normr, normar, normA, condA, normx<EOL>

Iterative solver for least-squares problems.

    lsmr solves the system of linear equations ``Ax = b``. If the system
    is inconsistent, it solves the least-squares problem ``min ||b - Ax||_2``.
    A is a rectangular matrix of dimension m-by-n, where all cases are
    allowed: m = n, m > n, or m < n. B is a vector of length m.
    The matrix A may be dense or sparse (usually sparse).

    Parameters
    ----------
    A : {matrix, sparse matrix, ndarray, LinearOperator}
        Matrix A in the linear system.
    b : (m,) ndarray
        Vector b in the linear system.
    damp : float
        Damping factor for regularized least-squares. `lsmr` solves
        the regularized least-squares problem::

         min ||(b) - (  A   )x||
             ||(0)   (damp*I) ||_2

        where damp is a scalar.  If damp is None or 0, the system
        is solved without regularization.
    atol, btol : float
        Stopping tolerances. `lsmr` continues iterations until a
        certain backward error estimate is smaller than some quantity
        depending on atol and btol.  Let ``r = b - Ax`` be the
        residual vector for the current approximate solution ``x``.
        If ``Ax = b`` seems to be consistent, ``lsmr`` terminates
        when ``norm(r) <= atol * norm(A) * norm(x) + btol * norm(b)``.
        Otherwise, lsmr terminates when ``norm(A^{T} r) <=
        atol * norm(A) * norm(r)``.  If both tolerances are 1.0e-6 (say),
        the final ``norm(r)`` should be accurate to about 6
        digits. (The final x will usually have fewer correct digits,
        depending on ``cond(A)`` and the size of LAMBDA.)  If `atol`
        or `btol` is None, a default value of 1.0e-6 will be used.
        Ideally, they should be estimates of the relative error in the
        entries of A and B respectively.  For example, if the entries
        of `A` have 7 correct digits, set atol = 1e-7. This prevents
        the algorithm from doing unnecessary work beyond the
        uncertainty of the input data.
    conlim : float
        `lsmr` terminates if an estimate of ``cond(A)`` exceeds
        `conlim`.  For compatible systems ``Ax = b``, conlim could be
        as large as 1.0e+12 (say).  For least-squares problems,
        `conlim` should be less than 1.0e+8. If `conlim` is None, the
        default value is 1e+8.  Maximum precision can be obtained by
        setting ``atol = btol = conlim = 0``, but the number of
        iterations may then be excessive.
    maxiter : int
        `lsmr` terminates if the number of iterations reaches
        `maxiter`.  The default is ``maxiter = min(m, n)``.  For
        ill-conditioned systems, a larger value of `maxiter` may be
        needed.
    show : bool
        Print iterations logs if ``show=True``.

    Returns
    -------
    x : ndarray of float
        Least-square solution returned.
    istop : int
        istop gives the reason for stopping::

          istop   = 0 means x=0 is a solution.
                  = 1 means x is an approximate solution to A*x = B,
                      according to atol and btol.
                  = 2 means x approximately solves the least-squares problem
                      according to atol.
                  = 3 means COND(A) seems to be greater than CONLIM.
                  = 4 is the same as 1 with atol = btol = eps (machine
                      precision)
                  = 5 is the same as 2 with atol = eps.
                  = 6 is the same as 3 with CONLIM = 1/eps.
                  = 7 means ITN reached maxiter before the other stopping
                      conditions were satisfied.

    itn : int
        Number of iterations used.
    normr : float
        ``norm(b-Ax)``
    normar : float
        ``norm(A^T (b - Ax))``
    norma : float
        ``norm(A)``
    conda : float
        Condition number of A.
    normx : float
        ``norm(x)``

    Notes
    -----

    .. versionadded:: 0.11.0

    References
    ----------
    .. [1] D. C.-L. Fong and M. A. Saunders,
           "LSMR: An iterative algorithm for sparse least-squares problems",
           SIAM J. Sci. Comput., vol. 33, pp. 2950-2971, 2011.
           http://arxiv.org/abs/1006.0758
    .. [2] LSMR Software, http://www.stanford.edu/~clfong/lsmr.html


def make_system(A, M, x0, b, xtype=None):

A_ = A<EOL>A = aslinearoperator(A)<EOL>if A.shape[<NUM_LIT:0>] != A.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>' % (A.shape,))<EOL><DEDENT>N = A.shape[<NUM_LIT:0>]<EOL>b = asanyarray(b)<EOL>if not (b.shape == (N,<NUM_LIT:1>) or b.shape == (N,)):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if b.dtype.char not in '<STR_LIT>':<EOL><INDENT>b = b.astype('<STR_LIT:d>')  <EOL><DEDENT>def postprocess(x):<EOL><INDENT>if isinstance(b,matrix):<EOL><INDENT>x = asmatrix(x)<EOL><DEDENT>return x.reshape(b.shape)<EOL><DEDENT>if xtype is None:<EOL><INDENT>if hasattr(A,'<STR_LIT>'):<EOL><INDENT>xtype = A.dtype.char<EOL><DEDENT>else:<EOL><INDENT>xtype = A.matvec(b).dtype.char<EOL><DEDENT>xtype = coerce(xtype, b.dtype.char)<EOL><DEDENT>else:<EOL><INDENT>warn('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning)<EOL>if xtype == <NUM_LIT:0>:<EOL><INDENT>xtype = b.dtype.char<EOL><DEDENT>else:<EOL><INDENT>if xtype not in '<STR_LIT>':<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>b = asarray(b,dtype=xtype)  <EOL>b = b.ravel()<EOL>if x0 is None:<EOL><INDENT>x = zeros(N, dtype=xtype)<EOL><DEDENT>else:<EOL><INDENT>x = array(x0, dtype=xtype)<EOL>if not (x.shape == (N,<NUM_LIT:1>) or x.shape == (N,)):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>x = x.ravel()<EOL><DEDENT>if M is None:<EOL><INDENT>if hasattr(A_,'<STR_LIT>'):<EOL><INDENT>psolve = A_.psolve<EOL><DEDENT>else:<EOL><INDENT>psolve = id<EOL><DEDENT>if hasattr(A_,'<STR_LIT>'):<EOL><INDENT>rpsolve = A_.rpsolve<EOL><DEDENT>else:<EOL><INDENT>rpsolve = id<EOL><DEDENT>if psolve is id and rpsolve is id:<EOL><INDENT>M = IdentityOperator(shape=A.shape, dtype=A.dtype)<EOL><DEDENT>else:<EOL><INDENT>M = LinearOperator(A.shape, matvec=psolve, rmatvec=rpsolve,<EOL>dtype=A.dtype)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>M = aslinearoperator(M)<EOL>if A.shape != M.shape:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>return A, M, x, b, postprocess<EOL>

Make a linear system Ax=b

    Parameters
    ----------
    A : LinearOperator
        sparse or dense matrix (or any valid input to aslinearoperator)
    M : {LinearOperator, Nones}
        preconditioner
        sparse or dense matrix (or any valid input to aslinearoperator)
    x0 : {array_like, None}
        initial guess to iterative method
    b : array_like
        right hand side
    xtype : {'f', 'd', 'F', 'D', None}
        dtype of the x vector

    Returns
    -------
    (A, M, x, b, postprocess)
        A : LinearOperator
            matrix of the linear system
        M : LinearOperator
            preconditioner
        x : rank 1 ndarray
            initial guess
        b : rank 1 ndarray
            right hand side
        postprocess : function
            converts the solution vector to the appropriate
            type and dimensions (e.g. (N,1) matrix)


def assert_allclose_cc(actual, desired, **kw):

try:<EOL><INDENT>assert_allclose(actual, desired, **kw)<EOL><DEDENT>except:<EOL><INDENT>assert_allclose(actual, conj(desired), **kw)<EOL><DEDENT>

Almost equal or complex conjugates almost equal


def svds(A, k=<NUM_LIT:6>, ncv=None, tol=<NUM_LIT:0>, which='<STR_LIT>', v0=None,<EOL>maxiter=None, return_singular_vectors=True):

if not (isinstance(A, LinearOperator) or isspmatrix(A)):<EOL><INDENT>A = np.asarray(A)<EOL><DEDENT>n, m = A.shape<EOL>if isinstance(A, LinearOperator):<EOL><INDENT>if n > m:<EOL><INDENT>X_dot = A.matvec<EOL>X_matmat = A.matmat<EOL>XH_dot = A.rmatvec<EOL><DEDENT>else:<EOL><INDENT>X_dot = A.rmatvec<EOL>XH_dot = A.matvec<EOL>dtype = getattr(A, '<STR_LIT>', None)<EOL>if dtype is None:<EOL><INDENT>dtype = A.dot(np.zeros([m,<NUM_LIT:1>])).dtype<EOL><DEDENT>def X_matmat(V):<EOL><INDENT>out = np.empty((V.shape[<NUM_LIT:1>], m), dtype=dtype)<EOL>for i, col in enumerate(V.T):<EOL><INDENT>out[i, :] = A.rmatvec(col.reshape(-<NUM_LIT:1>, <NUM_LIT:1>)).T<EOL><DEDENT>return out.T<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if n > m:<EOL><INDENT>X_dot = X_matmat = A.dot<EOL>XH_dot = _herm(A).dot<EOL><DEDENT>else:<EOL><INDENT>XH_dot = A.dot<EOL>X_dot = X_matmat = _herm(A).dot<EOL><DEDENT><DEDENT>def matvec_XH_X(x):<EOL><INDENT>return XH_dot(X_dot(x))<EOL><DEDENT>XH_X = LinearOperator(matvec=matvec_XH_X, dtype=A.dtype,<EOL>shape=(min(A.shape), min(A.shape)))<EOL>eigvals, eigvec = eigsh(XH_X, k=k, tol=tol ** <NUM_LIT:2>, maxiter=maxiter,<EOL>ncv=ncv, which=which, v0=v0)<EOL>if which == '<STR_LIT>':<EOL><INDENT>eigvals = np.maximum(eigvals.real, <NUM_LIT:0>)<EOL>t = eigvec.dtype.char.lower()<EOL>factor = {'<STR_LIT:f>': <NUM_LIT>, '<STR_LIT:d>': <NUM_LIT>}<EOL>cond = factor[t] * np.finfo(t).eps<EOL>cutoff = cond * np.max(eigvals)<EOL>above_cutoff = (eigvals > cutoff)<EOL>nlarge = above_cutoff.sum()<EOL>nsmall = k - nlarge<EOL>slarge = np.sqrt(eigvals[above_cutoff])<EOL>s = np.zeros_like(eigvals)<EOL>s[:nlarge] = slarge<EOL>if not return_singular_vectors:<EOL><INDENT>return s<EOL><DEDENT>if n > m:<EOL><INDENT>vlarge = eigvec[:, above_cutoff]<EOL>ularge = X_matmat(vlarge) / slarge<EOL>vhlarge = _herm(vlarge)<EOL><DEDENT>else:<EOL><INDENT>ularge = eigvec[:, above_cutoff]<EOL>vhlarge = _herm(X_matmat(ularge) / slarge)<EOL><DEDENT>u = _augmented_orthonormal_cols(ularge, nsmall)<EOL>vh = _augmented_orthonormal_rows(vhlarge, nsmall)<EOL><DEDENT>else:<EOL><INDENT>s = np.sqrt(eigvals)<EOL>if not return_singular_vectors:<EOL><INDENT>return s<EOL><DEDENT>if n > m:<EOL><INDENT>v = eigvec<EOL>u = X_matmat(v) / s<EOL>vh = _herm(v)<EOL><DEDENT>else:<EOL><INDENT>u = eigvec<EOL>vh = _herm(X_matmat(u) / s)<EOL><DEDENT><DEDENT>return u, s, vh<EOL>

Compute the largest k singular values/vectors for a sparse matrix.

    Parameters
    ----------
    A : {sparse matrix, LinearOperator}
        Array to compute the SVD on, of shape (M, N)
    k : int, optional
        Number of singular values and vectors to compute.
    ncv : int, optional
        The number of Lanczos vectors generated
        ncv must be greater than k+1 and smaller than n;
        it is recommended that ncv > 2*k
        Default: ``min(n, 2*k + 1)``
    tol : float, optional
        Tolerance for singular values. Zero (default) means machine precision.
    which : str, ['LM' | 'SM'], optional
        Which `k` singular values to find:

            - 'LM' : largest singular values
            - 'SM' : smallest singular values

        .. versionadded:: 0.12.0
    v0 : ndarray, optional
        Starting vector for iteration, of length min(A.shape). Should be an
        (approximate) right singular vector if N > M and a right singular vector
        otherwise.
        Default: random

        .. versionadded:: 0.12.0
    maxiter: int, optional
        Maximum number of iterations.

        .. versionadded:: 0.12.0
    return_singular_vectors : bool, optional
        Return singular vectors (True) in addition to singular values

        .. versionadded:: 0.12.0

    Returns
    -------
    u : ndarray, shape=(M, k)
        Unitary matrix having left singular vectors as columns.
    s : ndarray, shape=(k,)
        The singular values.
    vt : ndarray, shape=(k, N)
        Unitary matrix having right singular vectors as rows.

    Notes
    -----
    This is a naive implementation using ARPACK as an eigensolver
    on A.H * A or A * A.H, depending on which one is more efficient.


if ar.ndim == <NUM_LIT:2>:<EOL><INDENT>return ar<EOL><DEDENT>else:  <EOL><INDENT>aux = np.array(ar, copy=False)<EOL>aux.shape = (ar.shape[<NUM_LIT:0>], <NUM_LIT:1>)<EOL>return aux<EOL><DEDENT>

If the input array is 2D return it, if it is 1D, append a dimension,
making it a column vector.


if isinstance(A, LinearOperator):<EOL><INDENT>return A<EOL><DEDENT>elif isinstance(A, np.ndarray) or isinstance(A, np.matrix):<EOL><INDENT>if A.ndim > <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>A = np.atleast_2d(np.asarray(A))<EOL>return MatrixLinearOperator(A)<EOL><DEDENT>elif isspmatrix(A):<EOL><INDENT>return MatrixLinearOperator(A)<EOL><DEDENT>else:<EOL><INDENT>if hasattr(A, '<STR_LIT>') and hasattr(A, '<STR_LIT>'):<EOL><INDENT>rmatvec = None<EOL>dtype = None<EOL>if hasattr(A, '<STR_LIT>'):<EOL><INDENT>rmatvec = A.rmatvec<EOL><DEDENT>if hasattr(A, '<STR_LIT>'):<EOL><INDENT>dtype = A.dtype<EOL><DEDENT>return LinearOperator(A.shape, A.matvec,<EOL>rmatvec=rmatvec, dtype=dtype)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT>

Return A as a LinearOperator.

    'A' may be any of the following types:
     - ndarray
     - matrix
     - sparse matrix (e.g. csr_matrix, lil_matrix, etc.)
     - LinearOperator
     - An object with .shape and .matvec attributes

    See the LinearOperator documentation for additional information.

    Examples
    --------
    >>> from scipy import matrix
    >>> M = matrix( [[1,2,3],[4,5,6]], dtype='int32' )
    >>> aslinearoperator( M )
    <2x3 LinearOperator with dtype=int32>


def spilu(A, drop_tol=None, fill_factor=None, drop_rule=None, permc_spec=None,<EOL>diag_pivot_thresh=None, relax=None, panel_size=None, options=None):

if not isspmatrix_csc(A):<EOL><INDENT>A = csc_matrix(A)<EOL>warn('<STR_LIT>', SparseEfficiencyWarning)<EOL><DEDENT>A.sort_indices()<EOL>A = A.asfptype()  <EOL>M, N = A.shape<EOL>if (M != N):<EOL><INDENT>raise ValueError("<STR_LIT>")  <EOL><DEDENT>_options = dict(ILU_DropRule=drop_rule, ILU_DropTol=drop_tol,<EOL>ILU_FillFactor=fill_factor,<EOL>DiagPivotThresh=diag_pivot_thresh, ColPerm=permc_spec,<EOL>PanelSize=panel_size, Relax=relax)<EOL>if options is not None:<EOL><INDENT>_options.update(options)<EOL><DEDENT>return _superlu.gstrf(N, A.nnz, A.data, A.indices, A.indptr,<EOL>ilu=True, options=_options)<EOL>

Compute an incomplete LU decomposition for a sparse, square matrix.

The resulting object is an approximation to the inverse of `A`.

Parameters
----------
A : (N, N) array_like
    Sparse matrix to factorize
drop_tol : float, optional
    Drop tolerance (0 <= tol <= 1) for an incomplete LU decomposition.
    (default: 1e-4)
fill_factor : float, optional
    Specifies the fill ratio upper bound (>= 1.0) for ILU. (default: 10)
drop_rule : str, optional
    Comma-separated string of drop rules to use.
    Available rules: ``basic``, ``prows``, ``column``, ``area``,
    ``secondary``, ``dynamic``, ``interp``. (Default: ``basic,area``)

    See SuperLU documentation for details.
milu : str, optional
    Which version of modified ILU to use. (Choices: ``silu``,
    ``smilu_1``, ``smilu_2`` (default), ``smilu_3``.)

Remaining other options
    Same as for `splu`

Returns
-------
invA_approx : scipy.sparse.linalg.SuperLU
    Object, which has a ``solve`` method.

See also
--------
splu : complete LU decomposition

Notes
-----
To improve the better approximation to the inverse, you may need to
increase `fill_factor` AND decrease `drop_tol`.

This function uses the SuperLU library.


def _onenormest_matrix_power(A, p,<EOL>t=<NUM_LIT:2>, itmax=<NUM_LIT:5>, compute_v=False, compute_w=False, structure=None):

return scipy.sparse.linalg.onenormest(<EOL>MatrixPowerOperator(A, p, structure=structure))<EOL>

Efficiently estimate the 1-norm of A^p.

Parameters
----------
A : ndarray
    Matrix whose 1-norm of a power is to be computed.
p : int
    Non-negative integer power.
t : int, optional
    A positive parameter controlling the tradeoff between
    accuracy versus time and memory usage.
    Larger values take longer and use more memory
    but give more accurate output.
itmax : int, optional
    Use at most this many iterations.
compute_v : bool, optional
    Request a norm-maximizing linear operator input vector if True.
compute_w : bool, optional
    Request a norm-maximizing linear operator output vector if True.

Returns
-------
est : float
    An underestimate of the 1-norm of the sparse matrix.
v : ndarray, optional
    The vector such that ||Av||_1 == est*||v||_1.
    It can be thought of as an input to the linear operator
    that gives an output with particularly large norm.
w : ndarray, optional
    The vector Av which has relatively large 1-norm.
    It can be thought of as an output of the linear operator
    that is relatively large in norm compared to the input.


def __init__(self, A, structure=None, use_exact_onenorm=False):

self.A = A<EOL>self._A2 = None<EOL>self._A4 = None<EOL>self._A6 = None<EOL>self._A8 = None<EOL>self._A10 = None<EOL>self._d4_exact = None<EOL>self._d6_exact = None<EOL>self._d8_exact = None<EOL>self._d10_exact = None<EOL>self._d4_approx = None<EOL>self._d6_approx = None<EOL>self._d8_approx = None<EOL>self._d10_approx = None<EOL>self.ident = _ident_like(A)<EOL>self.structure = structure<EOL>self.use_exact_onenorm = use_exact_onenorm<EOL>

Initialize the object.

Parameters
----------
A : a dense or sparse square numpy matrix or ndarray
    The matrix to be exponentiated.
structure : str, optional
    A string describing the structure of matrix `A`.
    Only `upper_triangular` is currently supported.
use_exact_onenorm : bool, optional
    If True then only the exact one-norm of matrix powers and products
    will be used. Otherwise, the one-norm of powers and products
    may initially be estimated.


I = speye(A.shape[<NUM_LIT:0>], A.shape[<NUM_LIT:1>], dtype=A.dtype, format=A.format)<EOL>Ainv = spsolve(A, I)<EOL>return Ainv<EOL>

Compute the inverse of a sparse matrix

Parameters
----------
A : (M,M) ndarray or sparse matrix
    square matrix to be inverted

Returns
-------
Ainv : (M,M) ndarray or sparse matrix
    inverse of `A`

Notes
-----
This computes the sparse inverse of `A`.  If the inverse of `A` is expected
to be non-sparse, it will likely be faster to convert `A` to dense and use
scipy.linalg.inv.

.. versionadded:: 0.12.0


<EOL>if isinstance(A, (list, tuple)):<EOL><INDENT>A = np.asarray(A)<EOL><DEDENT>if len(A.shape) != <NUM_LIT:2> or A.shape[<NUM_LIT:0>] != A.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>structure = UPPER_TRIANGULAR if _is_upper_triangular(A) else None<EOL>use_exact_onenorm = A.shape[<NUM_LIT:0>] < <NUM_LIT:200><EOL>h = _ExpmPadeHelper(<EOL>A, structure=structure, use_exact_onenorm=use_exact_onenorm)<EOL>eta_1 = max(h.d4_loose, h.d6_loose)<EOL>if eta_1 < <NUM_LIT> and _ell(h.A, <NUM_LIT:3>) == <NUM_LIT:0>:<EOL><INDENT>U, V = h.pade3()<EOL>return _solve_P_Q(U, V, structure=structure)<EOL><DEDENT>eta_2 = max(h.d4_tight, h.d6_loose)<EOL>if eta_2 < <NUM_LIT> and _ell(h.A, <NUM_LIT:5>) == <NUM_LIT:0>:<EOL><INDENT>U, V = h.pade5()<EOL>return _solve_P_Q(U, V, structure=structure)<EOL><DEDENT>eta_3 = max(h.d6_tight, h.d8_loose)<EOL>if eta_3 < <NUM_LIT> and _ell(h.A, <NUM_LIT:7>) == <NUM_LIT:0>:<EOL><INDENT>U, V = h.pade7()<EOL>return _solve_P_Q(U, V, structure=structure)<EOL><DEDENT>if eta_3 < <NUM_LIT> and _ell(h.A, <NUM_LIT:9>) == <NUM_LIT:0>:<EOL><INDENT>U, V = h.pade9()<EOL>return _solve_P_Q(U, V, structure=structure)<EOL><DEDENT>eta_4 = max(h.d8_loose, h.d10_loose)<EOL>eta_5 = min(eta_3, eta_4)<EOL>theta_13 = <NUM_LIT><EOL>s = max(int(np.ceil(np.log2(eta_5 / theta_13))), <NUM_LIT:0>)<EOL>s = s + _ell(<NUM_LIT:2>**-s * h.A, <NUM_LIT>)<EOL>U, V = h.pade13_scaled(s)<EOL>X = _solve_P_Q(U, V, structure=structure)<EOL>if structure == UPPER_TRIANGULAR:<EOL><INDENT>X = _fragment_2_1(X, h.A, s)<EOL><DEDENT>else:<EOL><INDENT>for i in range(s):<EOL><INDENT>X = X.dot(X)<EOL><DEDENT><DEDENT>return X<EOL>

Compute the matrix exponential using Pade approximation.

Parameters
----------
A : (M,M) array_like or sparse matrix
    2D Array or Matrix (sparse or dense) to be exponentiated

Returns
-------
expA : (M,M) ndarray
    Matrix exponential of `A`

Notes
-----
This is algorithm (6.1) which is a simplification of algorithm (5.1).

.. versionadded:: 0.12.0

References
----------
.. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009)
       "A New Scaling and Squaring Algorithm for the Matrix Exponential."
       SIAM Journal on Matrix Analysis and Applications.
       31 (3). pp. 970-989. ISSN 1095-7162


def onenormest(A, t=<NUM_LIT:2>, itmax=<NUM_LIT:5>, compute_v=False, compute_w=False):

<EOL>if len(A.shape) != <NUM_LIT:2> or A.shape[<NUM_LIT:0>] != A.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>n = A.shape[<NUM_LIT:1>]<EOL>if t >= n:<EOL><INDENT>A_explicit = np.asarray(aslinearoperator(A).matmat(np.identity(n)))<EOL>if A_explicit.shape != (n, n):<EOL><INDENT>raise Exception('<STR_LIT>',<EOL>'<STR_LIT>' + str(A_explicit.shape))<EOL><DEDENT>col_abs_sums = abs(A_explicit).sum(axis=<NUM_LIT:0>)<EOL>if col_abs_sums.shape != (n, ):<EOL><INDENT>raise Exception('<STR_LIT>',<EOL>'<STR_LIT>' + str(col_abs_sums.shape))<EOL><DEDENT>argmax_j = np.argmax(col_abs_sums)<EOL>v = elementary_vector(n, argmax_j)<EOL>w = A_explicit[:, argmax_j]<EOL>est = col_abs_sums[argmax_j]<EOL><DEDENT>else:<EOL><INDENT>est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax)<EOL><DEDENT>if compute_v or compute_w:<EOL><INDENT>result = (est,)<EOL>if compute_v:<EOL><INDENT>result += (v,)<EOL><DEDENT>if compute_w:<EOL><INDENT>result += (w,)<EOL><DEDENT>return result<EOL><DEDENT>else:<EOL><INDENT>return est<EOL><DEDENT>

Compute a lower bound of the 1-norm of a sparse matrix.

Parameters
----------
A : ndarray or other linear operator
    A linear operator that can be transposed and that can
    produce matrix products.
t : int, optional
    A positive parameter controlling the tradeoff between
    accuracy versus time and memory usage.
    Larger values take longer and use more memory
    but give more accurate output.
itmax : int, optional
    Use at most this many iterations.
compute_v : bool, optional
    Request a norm-maximizing linear operator input vector if True.
compute_w : bool, optional
    Request a norm-maximizing linear operator output vector if True.

Returns
-------
est : float
    An underestimate of the 1-norm of the sparse matrix.
v : ndarray, optional
    The vector such that ||Av||_1 == est*||v||_1.
    It can be thought of as an input to the linear operator
    that gives an output with particularly large norm.
w : ndarray, optional
    The vector Av which has relatively large 1-norm.
    It can be thought of as an output of the linear operator
    that is relatively large in norm compared to the input.

Notes
-----
This is algorithm 2.4 of [1].

In [2] it is described as follows.
"This algorithm typically requires the evaluation of
about 4t matrix-vector products and almost invariably
produces a norm estimate (which is, in fact, a lower
bound on the norm) correct to within a factor 3."

.. versionadded:: 0.13.0

References
----------
.. [1] Nicholas J. Higham and Francoise Tisseur (2000),
       "A Block Algorithm for Matrix 1-Norm Estimation,
       with an Application to 1-Norm Pseudospectra."
       SIAM J. Matrix Anal. Appl. Vol. 21, No. 4, pp. 1185-1201.

.. [2] Awad H. Al-Mohy and Nicholas J. Higham (2009),
       "A new scaling and squaring algorithm for the matrix exponential."
       SIAM J. Matrix Anal. Appl. Vol. 31, No. 3, pp. 970-989.


<EOL>A_linear_operator = aslinearoperator(A)<EOL>AT_linear_operator = aslinearoperator(AT)<EOL>if itmax < <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if t < <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>n = A.shape[<NUM_LIT:0>]<EOL>if t >= n:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>nmults = <NUM_LIT:0><EOL>nresamples = <NUM_LIT:0><EOL>X = np.ones((n, t), dtype=float)<EOL>if t > <NUM_LIT:1>:<EOL><INDENT>for i in range(<NUM_LIT:1>, t):<EOL><INDENT>resample_column(i, X)<EOL><DEDENT>for i in range(t):<EOL><INDENT>while column_needs_resampling(i, X):<EOL><INDENT>resample_column(i, X)<EOL>nresamples += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>X /= float(n)<EOL>ind_hist = set()<EOL>est_old = <NUM_LIT:0><EOL>S = np.zeros((n, t), dtype=float)<EOL>k = <NUM_LIT:1><EOL>ind = None<EOL>while True:<EOL><INDENT>Y = np.asarray(A_linear_operator.matmat(X))<EOL>nmults += <NUM_LIT:1><EOL>mags = [norm_1d_1(Y[:, j]) for j in range(t)]<EOL>est = np.max(mags)<EOL>best_j = np.argmax(mags)<EOL>if est > est_old or k == <NUM_LIT:2>:<EOL><INDENT>if k >= <NUM_LIT:2>:<EOL><INDENT>ind_best = ind[best_j]<EOL><DEDENT>w = Y[:, best_j]<EOL><DEDENT>if k >= <NUM_LIT:2> and est <= est_old:<EOL><INDENT>est = est_old<EOL>break<EOL><DEDENT>est_old = est<EOL>S_old = S<EOL>if k > itmax:<EOL><INDENT>break<EOL><DEDENT>S = sign_round_up(Y)<EOL>if every_col_of_X_is_parallel_to_a_col_of_Y(S, S_old):<EOL><INDENT>break<EOL><DEDENT>if t > <NUM_LIT:1>:<EOL><INDENT>for i in range(t):<EOL><INDENT>while column_needs_resampling(i, S, S_old):<EOL><INDENT>resample_column(i, S)<EOL>nresamples += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>Z = np.asarray(AT_linear_operator.matmat(S))<EOL>nmults += <NUM_LIT:1><EOL>h = [norm_1d_inf(row) for row in Z]<EOL>if k >= <NUM_LIT:2> and max(h) == h[ind_best]:<EOL><INDENT>break<EOL><DEDENT>h_i_pairs = zip(h, range(n))<EOL>h, ind = zip(*sorted(h_i_pairs, reverse=True))<EOL>if t > <NUM_LIT:1>:<EOL><INDENT>if set(ind[:t]) <= ind_hist:<EOL><INDENT>break<EOL><DEDENT>unused_entries = [i for i in ind if i not in ind_hist]<EOL>used_entries = [i for i in ind if i in ind_hist]<EOL>ind = unused_entries + used_entries<EOL><DEDENT>for j in range(t):<EOL><INDENT>X[:, j] = elementary_vector(n, ind[j])<EOL><DEDENT>ind_hist.update(ind[:t])<EOL>k += <NUM_LIT:1><EOL><DEDENT>v = elementary_vector(n, ind_best)<EOL>return est, v, w, nmults, nresamples<EOL>

Compute a lower bound of the 1-norm of a sparse matrix.

Parameters
----------
A : ndarray or other linear operator
    A linear operator that can produce matrix products.
AT : ndarray or other linear operator
    The transpose of A.
t : int, optional
    A positive parameter controlling the tradeoff between
    accuracy versus time and memory usage.
itmax : int, optional
    Use at most this many iterations.

Returns
-------
est : float
    An underestimate of the 1-norm of the sparse matrix.
v : ndarray, optional
    The vector such that ||Av||_1 == est*||v||_1.
    It can be thought of as an input to the linear operator
    that gives an output with particularly large norm.
w : ndarray, optional
    The vector Av which has relatively large 1-norm.
    It can be thought of as an output of the linear operator
    that is relatively large in norm compared to the input.
nmults : int, optional
    The number of matrix products that were computed.
nresamples : int, optional
    The number of times a parallel column was observed,
    necessitating a re-randomization of the column.

Notes
-----
This is algorithm 2.4.


if axis is None:<EOL><INDENT>return int(self.indptr[-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>if axis < <NUM_LIT:0>:<EOL><INDENT>axis += <NUM_LIT:2><EOL><DEDENT>axis, _ = self._swap((axis, <NUM_LIT:1> - axis))<EOL>_, N = self._swap(self.shape)<EOL>if axis == <NUM_LIT:0>:<EOL><INDENT>return _compat_bincount(downcast_intp_index(self.indices),<EOL>minlength=N)<EOL><DEDENT>elif axis == <NUM_LIT:1>:<EOL><INDENT>return np.diff(self.indptr)<EOL><DEDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>

Get the count of explicitly-stored values (nonzeros)

        Parameters
        ----------
        axis : None, 0, or 1
            Select between the number of values across the whole matrix, in
            each column, or in each row.


<EOL>major_name,minor_name = self._swap(('<STR_LIT>','<STR_LIT>'))<EOL>major_dim,minor_dim = self._swap(self.shape)<EOL>if self.indptr.dtype.kind != '<STR_LIT:i>':<EOL><INDENT>warn("<STR_LIT>"<EOL>% self.indptr.dtype.name)<EOL><DEDENT>if self.indices.dtype.kind != '<STR_LIT:i>':<EOL><INDENT>warn("<STR_LIT>"<EOL>% self.indices.dtype.name)<EOL><DEDENT>idx_dtype = get_index_dtype((self.indptr, self.indices))<EOL>self.indptr = np.asarray(self.indptr, dtype=idx_dtype)<EOL>self.indices = np.asarray(self.indices, dtype=idx_dtype)<EOL>self.data = to_native(self.data)<EOL>if self.data.ndim != <NUM_LIT:1> or self.indices.ndim != <NUM_LIT:1> or self.indptr.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if (len(self.indptr) != major_dim + <NUM_LIT:1>):<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>(len(self.indptr), major_dim + <NUM_LIT:1>))<EOL><DEDENT>if (self.indptr[<NUM_LIT:0>] != <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (len(self.indices) != len(self.data)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (self.indptr[-<NUM_LIT:1>] > len(self.indices)):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self.prune()<EOL>if full_check:<EOL><INDENT>if self.nnz > <NUM_LIT:0>:<EOL><INDENT>if self.indices.max() >= minor_dim:<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>(minor_name,minor_dim))<EOL><DEDENT>if self.indices.min() < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>minor_name)<EOL><DEDENT>if np.diff(self.indptr).min() < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>

check whether the matrix format is valid

        Parameters
        ==========

            - full_check : {bool}
                - True  - rigorous check, O(N) operations : default
                - False - basic check, O(1) operations


<EOL>if not hasattr(self,'<STR_LIT>'):<EOL><INDENT>fn = _sparsetools.csr_has_sorted_indices<EOL>self._has_sorted_indices =fn(len(self.indptr) - <NUM_LIT:1>, self.indptr, self.indices)<EOL><DEDENT>return self._has_sorted_indices<EOL>

Determine whether the matrix has sorted indices

        Returns
            - True: if the indices of the matrix are in sorted order
            - False: otherwise


order = np.argsort(i, kind='<STR_LIT>')  <EOL>i = i.take(order, mode='<STR_LIT>')<EOL>j = j.take(order, mode='<STR_LIT>')<EOL>x = x.take(order, mode='<STR_LIT>')<EOL>do_sort = self.has_sorted_indices<EOL>idx_dtype = get_index_dtype((self.indices, self.indptr),<EOL>maxval=(self.indptr[-<NUM_LIT:1>] + x.size))<EOL>self.indptr = np.asarray(self.indptr, dtype=idx_dtype)<EOL>self.indices = np.asarray(self.indices, dtype=idx_dtype)<EOL>i = np.asarray(i, dtype=idx_dtype)<EOL>j = np.asarray(j, dtype=idx_dtype)<EOL>indices_parts = []<EOL>data_parts = []<EOL>ui, ui_indptr = _compat_unique(i, return_index=True)<EOL>ui_indptr = np.append(ui_indptr, len(j))<EOL>new_nnzs = np.diff(ui_indptr)<EOL>prev = <NUM_LIT:0><EOL>for c, (ii, js, je) in enumerate(izip(ui, ui_indptr, ui_indptr[<NUM_LIT:1>:])):<EOL><INDENT>start = self.indptr[prev]<EOL>stop = self.indptr[ii]<EOL>indices_parts.append(self.indices[start:stop])<EOL>data_parts.append(self.data[start:stop])<EOL>uj, uj_indptr = _compat_unique(j[js:je][::-<NUM_LIT:1>], return_index=True)<EOL>if len(uj) == je - js:<EOL><INDENT>indices_parts.append(j[js:je])<EOL>data_parts.append(x[js:je])<EOL><DEDENT>else:<EOL><INDENT>indices_parts.append(j[js:je][::-<NUM_LIT:1>][uj_indptr])<EOL>data_parts.append(x[js:je][::-<NUM_LIT:1>][uj_indptr])<EOL>new_nnzs[c] = len(uj)<EOL><DEDENT>prev = ii<EOL><DEDENT>start = self.indptr[ii]<EOL>indices_parts.append(self.indices[start:])<EOL>data_parts.append(self.data[start:])<EOL>self.indices = np.concatenate(indices_parts)<EOL>self.data = np.concatenate(data_parts)<EOL>nnzs = np.asarray(np.ediff1d(self.indptr, to_begin=<NUM_LIT:0>), dtype=idx_dtype)<EOL>nnzs[<NUM_LIT:1>:][ui] += new_nnzs<EOL>self.indptr = np.cumsum(nnzs, out=nnzs)<EOL>if do_sort:<EOL><INDENT>self.has_sorted_indices = False<EOL>self.sort_indices()<EOL><DEDENT>self.check_format(full_check=False)<EOL>

Inserts new nonzero at each (i, j) with value x

        Here (i,j) index major and minor respectively.
        i, j and x must be non-empty, 1d arrays.
        Inserts each major group (e.g. all entries per row) at a time.
        Maintains has_sorted_indices property.
        Modifies i, j, x in place.


Returns a matrix with the same sparsity structure as self,
        but with different data.  By default the structure arrays
        (i.e. .indptr and .indices) are copied.


major_dim,minor_dim = self._swap(self.shape)<EOL>data = self.data<EOL>minor_indices = self.indices<EOL>if copy:<EOL><INDENT>data = data.copy()<EOL>minor_indices = minor_indices.copy()<EOL><DEDENT>major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype)<EOL>_sparsetools.expandptr(major_dim,self.indptr,major_indices)<EOL>row,col = self._swap((major_indices,minor_indices))<EOL>from .coo import coo_matrix<EOL>return coo_matrix((data,(row,col)), self.shape)<EOL>

Return a COOrdinate representation of this matrix

        When copy=False the index and data arrays are not copied.


def _get_slice(self, i, start, stop, stride, shape):

if stride != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if stop <= start:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>indices = []<EOL>for ind in xrange(self.indptr[i], self.indptr[i+<NUM_LIT:1>]):<EOL><INDENT>if self.indices[ind] >= start and self.indices[ind] < stop:<EOL><INDENT>indices.append(ind)<EOL><DEDENT><DEDENT>index = self.indices[indices] - start<EOL>data = self.data[indices]<EOL>indptr = np.array([<NUM_LIT:0>, len(indices)])<EOL>return self.__class__((data, index, indptr), shape=shape,<EOL>dtype=self.dtype)<EOL>

Returns a copy of the elements
            [i, start:stop:string] for row-oriented matrices
            [start:stop:string, i] for column-oriented matrices


<EOL>fn = getattr(_sparsetools, self.format + "<STR_LIT>")<EOL>y = np.empty(min(self.shape), dtype=upcast(self.dtype))<EOL>fn(self.shape[<NUM_LIT:0>], self.shape[<NUM_LIT:1>], self.indptr, self.indices, self.data, y)<EOL>return y<EOL>


def toarray(self, order=None, out=None):

return self.tocoo(copy=False).toarray(order=order, out=out)<EOL>

See the docstring for `spmatrix.toarray`.


if self.has_canonical_format:<EOL><INDENT>return<EOL><DEDENT>self.sort_indices()<EOL>fn = _sparsetools.csr_sum_duplicates<EOL>M,N = self._swap(self.shape)<EOL>fn(M, N, self.indptr, self.indices, self.data)<EOL>self.prune()  <EOL>self.has_canonical_format = True<EOL>

Eliminate duplicate matrix entries by adding them together

        The is an *in place* operation


t = _upcast_memo.get(args)<EOL>if t is not None:<EOL><INDENT>return t<EOL><DEDENT>t = upcast(*map(np.dtype, args))<EOL>_upcast_memo[args] = t<EOL>return t<EOL>

Same as `upcast` but taking dtype.char as input (faster).


return (np.array([<NUM_LIT:0>], dtype=dtype) * scalar).dtype<EOL>

Determine data type for binary operation between an array of
    type `dtype` and a scalar.


return np.isscalar(x) or (isdense(x) and x.ndim == <NUM_LIT:0>)<EOL>

Is x either a scalar, an array scalar, or a 0-dim array?


def getdtype(dtype, a=None, default=None):

<EOL>canCast = True<EOL>if dtype is None:<EOL><INDENT>try:<EOL><INDENT>newdtype = a.dtype<EOL><DEDENT>except AttributeError:<EOL><INDENT>if default is not None:<EOL><INDENT>newdtype = np.dtype(default)<EOL>canCast = False<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>newdtype = np.dtype(dtype)<EOL>if newdtype == np.object_:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT><DEDENT>return newdtype<EOL>

Function used to simplify argument processing.  If 'dtype' is not
    specified (is None), returns a.dtype; otherwise returns a np.dtype
    object created from the specified dtype argument.  If 'dtype' and 'a'
    are both None, construct a data type out of the 'default' parameter.
    Furthermore, 'dtype' must be in 'allowed' set.


new = lil_matrix((<NUM_LIT:1>, self.shape[<NUM_LIT:1>]), dtype=self.dtype)<EOL>new.rows[<NUM_LIT:0>] = self.rows[i][:]<EOL>new.data[<NUM_LIT:0>] = self.data[i][:]<EOL>return new<EOL>


d = self._process_toarray_args(order, out)<EOL>for i, row in enumerate(self.rows):<EOL><INDENT>for pos, j in enumerate(row):<EOL><INDENT>d[i, j] = self.data[i][pos]<EOL><DEDENT><DEDENT>return d<EOL>


<EOL>from .csr import csr_matrix<EOL>m = self.shape[<NUM_LIT:0>]<EOL>if i < <NUM_LIT:0>:<EOL><INDENT>i += m<EOL><DEDENT>if i < <NUM_LIT:0> or i >= m:<EOL><INDENT>raise IndexError("<STR_LIT>")<EOL><DEDENT>row_selector = csr_matrix(([<NUM_LIT:1>], [[<NUM_LIT:0>], [i]]), shape=(<NUM_LIT:1>,m), dtype=self.dtype)<EOL>return row_selector * self<EOL>

Returns a copy of row i of the matrix, as a (1 x n) sparse
        matrix (row vector).


def todense(self, order=None, out=None):

return np.asmatrix(self.toarray(order=order, out=out))<EOL>

Return a dense matrix representation of this matrix.

Parameters
----------
order : {'C', 'F'}, optional
    Whether to store multi-dimensional data in C (row-major)
    or Fortran (column-major) order in memory. The default
    is 'None', indicating the NumPy default of C-ordered.
    Cannot be specified in conjunction with the `out`
    argument.

out : ndarray, 2-dimensional, optional
    If specified, uses this array (or `numpy.matrix`) as the
    output buffer instead of allocating a new array to
    return. The provided array must have the same shape and
    dtype as the sparse matrix on which you are calling the
    method.

Returns
-------
arr : numpy.matrix, 2-dimensional
    A NumPy matrix object with the same shape and containing
    the same data represented by the sparse matrix, with the
    requested memory order. If `out` was passed and was an
    array (rather than a `numpy.matrix`), it will be filled
    with the appropriate values and returned wrapped in a
    `numpy.matrix` object that shares the same memory.


return self.tocsr().multiply(other)<EOL>

Point-wise multiplication by another matrix