Esempio n. 1
0
    def test_fix_with_subclass(self):
        class MyArray(nx.ndarray):
            def __new__(cls, data, metadata=None):
                res = nx.array(data, copy=True).view(cls)
                res.metadata = metadata
                return res

            def __array_wrap__(self, obj, context=None):
                if isinstance(obj, MyArray):
                    obj.metadata = self.metadata
                return obj

            def __array_finalize__(self, obj):
                self.metadata = getattr(obj, 'metadata', None)
                return self

        a = nx.array([1.1, -1.1])
        m = MyArray(a, metadata='foo')
        f = ufl.fix(m)
        assert_array_equal(f, nx.array([1, -1]))
        assert_(isinstance(f, MyArray))
        assert_equal(f.metadata, 'foo')

        # check 0d arrays don't decay to scalars
        m0d = m[0,...]
        m0d.metadata = 'bar'
        f0d = ufl.fix(m0d)
        assert_(isinstance(f0d, MyArray))
        assert_equal(f0d.metadata, 'bar')
Esempio n. 2
0
def assert_array_compare(comparison, x, y, err_msg='', verbose=True,
                         header=''):
    from numpy.core import array, isnan, any
    x = array(x, copy=False, subok=True)
    y = array(y, copy=False, subok=True)

    def isnumber(x):
        return x.dtype.char in '?bhilqpBHILQPfdgFDG'

    try:
        cond = (x.shape==() or y.shape==()) or x.shape == y.shape
        if not cond:
            msg = build_err_msg([x, y],
                                err_msg
                                + '\n(shapes %s, %s mismatch)' % (x.shape,
                                                                  y.shape),
                                verbose=verbose, header=header,
                                names=('x', 'y'))
            if not cond :
                raise AssertionError(msg)

        if (isnumber(x) and isnumber(y)) and (any(isnan(x)) or any(isnan(y))):
            # Handling nan: we first check that x and y have the nan at the
            # same locations, and then we mask the nan and do the comparison as
            # usual.
            xnanid = isnan(x)
            ynanid = isnan(y)
            try:
                assert_array_equal(xnanid, ynanid)
            except AssertionError:
                msg = build_err_msg([x, y],
                                    err_msg
                                    + '\n(x and y nan location mismatch %s, ' \
                                    '%s mismatch)' % (xnanid, ynanid),
                                    verbose=verbose, header=header,
                                    names=('x', 'y'))
            val = comparison(x[~xnanid], y[~ynanid])
        else:
            val = comparison(x,y)
        if isinstance(val, bool):
            cond = val
            reduced = [0]
        else:
            reduced = val.ravel()
            cond = reduced.all()
            reduced = reduced.tolist()
        if not cond:
            match = 100-100.0*reduced.count(1)/len(reduced)
            msg = build_err_msg([x, y],
                                err_msg
                                + '\n(mismatch %s%%)' % (match,),
                                verbose=verbose, header=header,
                                names=('x', 'y'))
            if not cond :
                raise AssertionError(msg)
    except ValueError:
        msg = build_err_msg([x, y], err_msg, verbose=verbose, header=header,
                            names=('x', 'y'))
        raise ValueError(msg)
Esempio n. 3
0
 def test_3D_array(self):
     a = array([[1, 2], [1, 2]])
     b = array([[2, 3], [2, 3]])
     a = array([a, a])
     b = array([b, b])
     res = [atleast_2d(a), atleast_2d(b)]
     desired = [a, b]
     assert_array_equal(res, desired)
Esempio n. 4
0
    def test_bad_out_shape(self):
        a = array([1, 2])
        b = array([3, 4])

        assert_raises(ValueError, concatenate, (a, b), out=np.empty(5))
        assert_raises(ValueError, concatenate, (a, b), out=np.empty((4,1)))
        assert_raises(ValueError, concatenate, (a, b), out=np.empty((1,4)))
        concatenate((a, b), out=np.empty(4))
Esempio n. 5
0
 def test_3D_array(self):
     a = array([[1, 2], [1, 2]])
     b = array([[2, 3], [2, 3]])
     a = array([a, a])
     b = array([b, b])
     res = map(atleast_1d, [a, b])
     desired = [a, b]
     assert_array_equal(res, desired)
Esempio n. 6
0
 def test_log2(self):
     a = nx.array([4.5, 2.3, 6.5])
     out = nx.zeros(a.shape, float)
     tgt = nx.array([2.169925, 1.20163386, 2.70043972])
     res = ufl.log2(a)
     assert_almost_equal(res, tgt)
     res = ufl.log2(a, out)
     assert_almost_equal(res, tgt)
     assert_almost_equal(out, tgt)
Esempio n. 7
0
def test_stack():
    # non-iterable input
    assert_raises(TypeError, stack, 1)

    # 0d input
    for input_ in [(1, 2, 3),
                   [np.int32(1), np.int32(2), np.int32(3)],
                   [np.array(1), np.array(2), np.array(3)]]:
        assert_array_equal(stack(input_), [1, 2, 3])
    # 1d input examples
    a = np.array([1, 2, 3])
    b = np.array([4, 5, 6])
    r1 = array([[1, 2, 3], [4, 5, 6]])
    assert_array_equal(np.stack((a, b)), r1)
    assert_array_equal(np.stack((a, b), axis=1), r1.T)
    # all input types
    assert_array_equal(np.stack(list([a, b])), r1)
    assert_array_equal(np.stack(array([a, b])), r1)
    # all shapes for 1d input
    arrays = [np.random.randn(3) for _ in range(10)]
    axes = [0, 1, -1, -2]
    expected_shapes = [(10, 3), (3, 10), (3, 10), (10, 3)]
    for axis, expected_shape in zip(axes, expected_shapes):
        assert_equal(np.stack(arrays, axis).shape, expected_shape)
    assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=2)
    assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=-3)
    # all shapes for 2d input
    arrays = [np.random.randn(3, 4) for _ in range(10)]
    axes = [0, 1, 2, -1, -2, -3]
    expected_shapes = [(10, 3, 4), (3, 10, 4), (3, 4, 10),
                       (3, 4, 10), (3, 10, 4), (10, 3, 4)]
    for axis, expected_shape in zip(axes, expected_shapes):
        assert_equal(np.stack(arrays, axis).shape, expected_shape)
    # empty arrays
    assert_(stack([[], [], []]).shape == (3, 0))
    assert_(stack([[], [], []], axis=1).shape == (0, 3))
    # out
    out = np.zeros_like(r1)
    np.stack((a, b), out=out)
    assert_array_equal(out, r1)
    # edge cases
    assert_raises_regex(ValueError, 'need at least one array', stack, [])
    assert_raises_regex(ValueError, 'must have the same shape',
                        stack, [1, np.arange(3)])
    assert_raises_regex(ValueError, 'must have the same shape',
                        stack, [np.arange(3), 1])
    assert_raises_regex(ValueError, 'must have the same shape',
                        stack, [np.arange(3), 1], axis=1)
    assert_raises_regex(ValueError, 'must have the same shape',
                        stack, [np.zeros((3, 3)), np.zeros(3)], axis=1)
    assert_raises_regex(ValueError, 'must have the same shape',
                        stack, [np.arange(2), np.arange(3)])
    # generator is deprecated
    with assert_warns(FutureWarning):
        result = stack((x for x in range(3)))
    assert_array_equal(result, np.array([0, 1, 2]))
Esempio n. 8
0
    def test_isneginf(self):
        a = nx.array([nx.inf, -nx.inf, nx.nan, 0.0, 3.0, -3.0])
        out = nx.zeros(a.shape, bool)
        tgt = nx.array([False, True, False, False, False, False])

        res = ufl.isneginf(a)
        assert_equal(res, tgt)
        res = ufl.isneginf(a, out)
        assert_equal(res, tgt)
        assert_equal(out, tgt)
Esempio n. 9
0
    def test_fix(self):
        a = nx.array([[1.0, 1.1, 1.5, 1.8], [-1.0, -1.1, -1.5, -1.8]])
        out = nx.zeros(a.shape, float)
        tgt = nx.array([[1., 1., 1., 1.], [-1., -1., -1., -1.]])

        res = ufl.fix(a)
        assert_equal(res, tgt)
        res = ufl.fix(a, out)
        assert_equal(res, tgt)
        assert_equal(out, tgt)
        assert_equal(ufl.fix(3.14), 3)
Esempio n. 10
0
def Trebuchet1(t, state, param):
	g = param
	Theta + dTheta = state
	f   = array([(A*dTheta**2*h*n - A*dTheta**2*h*s - A*g*n + A*g*s - 2*M*g*n + 2*g*m*s)*cos(Theta)/2])
	m   = array([
		[A*(n + s)**2/12 + A*(4*h**2 - 4*h*(n - s)*sin(Theta) + (n - s)**2)/4 + M*n**2 + m*s**2],
		])
	n   = array([0])
	if h - s*sin(Theta) < 0:
		n = array([-g*m*s*cos(Theta)])
	f = f + n
	return concatenate((solve(m,f),[dTheta]))
Esempio n. 11
0
def test_stack():
    # non-iterable input
    assert_raises(TypeError, stack, 1)

    # 0d input
    for input_ in [(1, 2, 3),
                   [np.int32(1), np.int32(2), np.int32(3)],
                   [np.array(1), np.array(2), np.array(3)]]:
        assert_array_equal(stack(input_), [1, 2, 3])
    # 1d input examples
    a = np.array([1, 2, 3])
    b = np.array([4, 5, 6])
    r1 = array([[1, 2, 3], [4, 5, 6]])
    assert_array_equal(np.stack((a, b)), r1)
    assert_array_equal(np.stack((a, b), axis=1), r1.T)
    # all input types
    assert_array_equal(np.stack(list([a, b])), r1)
    assert_array_equal(np.stack(array([a, b])), r1)
    # all shapes for 1d input
    arrays = [np.random.randn(3) for _ in range(10)]
    axes = [0, 1, -1, -2]
    expected_shapes = [(10, 3), (3, 10), (3, 10), (10, 3)]
    for axis, expected_shape in zip(axes, expected_shapes):
        assert_equal(np.stack(arrays, axis).shape, expected_shape)
    assert_raises_regex(IndexError, 'out of bounds', stack, arrays, axis=2)
    assert_raises_regex(IndexError, 'out of bounds', stack, arrays, axis=-3)
    # all shapes for 2d input
    arrays = [np.random.randn(3, 4) for _ in range(10)]
    axes = [0, 1, 2, -1, -2, -3]
    expected_shapes = [(10, 3, 4), (3, 10, 4), (3, 4, 10),
                        (3, 4, 10), (3, 10, 4), (10, 3, 4)]
    for axis, expected_shape in zip(axes, expected_shapes):
        assert_equal(np.stack(arrays, axis).shape, expected_shape)
    # empty arrays
    assert_(stack([[], [], []]).shape == (3, 0))
    assert_(stack([[], [], []], axis=1).shape == (0, 3))
    # edge cases
    assert_raises_regex(ValueError, 'need at least one array', stack, [])
    assert_raises_regex(ValueError, 'must have the same shape',
                        stack, [1, np.arange(3)])
    assert_raises_regex(ValueError, 'must have the same shape',
                        stack, [np.arange(3), 1])
    assert_raises_regex(ValueError, 'must have the same shape',
                        stack, [np.arange(3), 1], axis=1)
    assert_raises_regex(ValueError, 'must have the same shape',
                        stack, [np.zeros((3, 3)), np.zeros(3)], axis=1)
    assert_raises_regex(ValueError, 'must have the same shape',
                        stack, [np.arange(2), np.arange(3)])
    # np.matrix
    m = np.matrix([[1, 2], [3, 4]])
    assert_raises_regex(ValueError, 'shape too large to be a matrix',
                        stack, [m, m])
Esempio n. 12
0
def Trebuchet3(t, state, param):
	g = param
	Theta + dTheta = state
	f   = array([A*dTheta**2*h*(n - s)*cos(Theta)/2 - A*g*(n - s)*cos(Theta)/2 - M*g*n*cos(Theta) + dPsi*dTheta*m*q*s*cos(Psi) + dPsi*m*q*s*(dPsi + dTheta)*cos(Psi) - g*m*(q*(sin(Psi)*cos(Theta) + sin(Theta)*cos(Psi)) - s*cos(Theta)), m*q*(-dTheta**2*s*cos(Psi) - g*sin(Psi)*cos(Theta) - g*sin(Theta)*cos(Psi))])
	m   = array([
		[A*(n + s)**2/12 + A*(4*h**2 - 4*h*(n - s)*sin(Theta) + (n - s)**2)/4 + M*n**2 + m*q**2 - 2*m*q*s*sin(Psi) + m*s**2, m*q*(q - s*sin(Psi))],
		[m*q*(q - s*sin(Psi)), m*q**2],
		])
	n   = array([0, 0])
	if h + q*(sin(Psi)*sin(Theta) - cos(Psi)*cos(Theta)) - s*sin(Theta) < 0:
		n = array([g*m*(q*(sin(Psi)*cos(Theta) + sin(Theta)*cos(Psi))*((sin(Psi)*sin(Theta) - cos(Psi)*cos(Theta))**2 + (sin(Psi)*cos(Theta) + sin(Theta)*cos(Psi))**2) - s*cos(Theta)), g*m*q*(sin(Psi)*cos(Theta) + sin(Theta)*cos(Psi))*((sin(Psi)*sin(Theta) - cos(Psi)*cos(Theta))**2 + (sin(Psi)*cos(Theta) + sin(Theta)*cos(Psi))**2)])
	f = f + n
	return concatenate((solve(m,f),[dTheta, dPsi]))
Esempio n. 13
0
def Trebuchet2(t, state, param):
	g = param
	Theta + dTheta = state
	f   = array([A*dTheta**2*h*(n - s)*cos(Theta)/2 - A*g*(n - s)*cos(Theta)/2 - M*dPhi*dTheta*n*p*cos(Phi) - M*dPhi*n*p*(dPhi + dTheta)*cos(Phi) - M*g*(n*cos(Theta) + p*(sin(Phi)*cos(Theta) + sin(Theta)*cos(Phi))) + g*m*s*cos(Theta), M*p*(dTheta**2*n*cos(Phi) - g*sin(Phi)*cos(Theta) - g*sin(Theta)*cos(Phi))])
	m   = array([
		[A*(n + s)**2/12 + A*(4*h**2 - 4*h*(n - s)*sin(Theta) + (n - s)**2)/4 + M*n**2 + 2*M*n*p*sin(Phi) + M*p**2 + m*s**2, M*p*(n*sin(Phi) + p)],
		[M*p*(n*sin(Phi) + p), M*p**2],
		])
	n   = array([0, 0])
	if h - s*sin(Theta) < 0:
		n = array([-g*m*s*cos(Theta), 0])
	f = f + n
	return concatenate((solve(m,f),[dTheta, dPhi]))
Esempio n. 14
0
    def test_isneginf(self):
        a = nx.array([nx.inf, -nx.inf, nx.nan, 0.0, 3.0, -3.0])
        out = nx.zeros(a.shape, bool)
        tgt = nx.array([False, True, False, False, False, False])

        res = ufl.isneginf(a)
        assert_equal(res, tgt)
        res = ufl.isneginf(a, out)
        assert_equal(res, tgt)
        assert_equal(out, tgt)

        a = a.astype(np.complex)
        with assert_raises(TypeError):
            ufl.isneginf(a)
Esempio n. 15
0
def DifferentialEquation(t, state, param):
	[h, o, p, q, r, n, m, M, g] = param
	[thetaDot, phiDot, theta, phi] = state
	force = array([0, 0, -o*sin(theta)*Derivative(theta, t)**2 + o*cos(theta)*Derivative(theta, t, t) - (h - y(t))*sin(theta)*Derivative(theta, t, t) - (h - y(t))*cos(theta)*Derivative(theta, t)**2 + 2*sin(theta)*Derivative(theta, t)*Derivative(y(t), t)])
	mass  = array([
		[0, 0, 0],
		[0, 0, 0],
		[0, 0, cos(theta)],
		])
	constraint  = array([0, 0])
	if -r*sin(phi) + (-p - q)*sin(theta) + y(t) < 0:
		constraint = array([-g*m*(p + q)*cos(theta), -g*m*r*cos(phi)])
	force = force + constraint
	return concatenate((solve(mass,force),[thetaDot, phiDot]))
    def test_fix_with_subclass(self):
        class MyArray(nx.ndarray):
            def __new__(cls, data, metadata=None):
                res = nx.array(data, copy=True).view(cls)
                res.metadata = metadata
                return res
            def __array_wrap__(self, obj, context=None):
                obj.metadata = self.metadata
                return obj

        a = nx.array([1.1, -1.1])
        m = MyArray(a, metadata='foo')
        f = ufl.fix(m)
        assert_array_equal(f, nx.array([1,-1]))
        assert_(isinstance(f, MyArray))
        assert_equal(f.metadata, 'foo')
Esempio n. 17
0
def load(filepath, pos_filepath):
    """
    :param filepath: fits image path
    :return: an Image
    """

    # load image data information
    data = pyfits.getdata(filepath, hdu=0)
    primary = Header(pyfits.getheader(filepath, 0))
    headers = [primary]
    extcount = int(primary.get("NEXTEND", 0))

    for idx in range(1, extcount):
        ext = Header(pyfits.getheader(filepath, idx))
        headers.append(ext)

    # load position information
    pos_primary = Header(pyfits.getheader(pos_filepath, 0))
    pos_headers = [pos_primary]
    pos_extcount = int(pos_primary.get("NEXTEND", 0))

    for idx in range(1, pos_extcount):
        ext = Header(pyfits.getheader(pos_filepath, idx))
        pos_headers.append(ext)

    return Image(array(data), headers, pos_headers)
Esempio n. 18
0
def ihfft(a, n=None, axis=-1, norm=None):
    """
    Compute the inverse FFT of a signal that has Hermitian symmetry.

    Parameters
    ----------
    a : array_like
        Input array.
    n : int, optional
        Length of the inverse FFT, the number of points along
        transformation axis in the input to use.  If `n` is smaller than
        the length of the input, the input is cropped.  If it is larger,
        the input is padded with zeros. If `n` is not given, the length of
        the input along the axis specified by `axis` is used.
    axis : int, optional
        Axis over which to compute the inverse FFT. If not given, the last
        axis is used.
    norm : {None, "ortho"}, optional
        Normalization mode (see `numpy.fft`). Default is None.

        .. versionadded:: 1.10.0

    Returns
    -------
    out : complex ndarray
        The truncated or zero-padded input, transformed along the axis
        indicated by `axis`, or the last one if `axis` is not specified.
        The length of the transformed axis is ``n//2 + 1``.

    See also
    --------
    hfft, irfft

    Notes
    -----
    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
    opposite case: here the signal has Hermitian symmetry in the time
    domain and is real in the frequency domain. So here it's `hfft` for
    which you must supply the length of the result if it is to be odd:

    * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
    * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.

    Examples
    --------
    >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
    >>> np.fft.ifft(spectrum)
    array([ 1.+0.j,  2.-0.j,  3.+0.j,  4.+0.j,  3.+0.j,  2.-0.j])
    >>> np.fft.ihfft(spectrum)
    array([ 1.-0.j,  2.-0.j,  3.-0.j,  4.-0.j])

    """
    # The copy may be required for multithreading.
    a = array(a, copy=True, dtype=float)
    if n is None:
        n = a.shape[axis]
    unitary = _unitary(norm)
    output = conjugate(rfft(a, n, axis))
    return output * (1 / (sqrt(n) if unitary else n))
def schwarz_christoffel_coeff(points):
  a = exp(2j*pi*linspace(0, 1, len(points), endpoint=False))
  a.shape = (1, -1)

  p = [points[-1]] + points + points[0:1]
  b = array([ (angle(  (p[k-1]-p[k])/(p[k+1]-p[k]) )/pi)%2.0 - 1.0
              for k in xrange(1, len(p)-1) ])
  b.shape = (1,-1)

  return (a,b)
Esempio n. 20
0
  def __init__(self, inc):
#    pdb.set_trace()
    self.lastUsedNumpy = 1 # Start out toggling to slow call
    self.increment = inc
    self.seed = 37
    rstate = numpy.random.get_state() # Backup the generator state.
    numpy.random.seed(37) # Set the generator state.
    alpha = array([1.0, 2.0, 1.0, 5.0, 7.0, 9.0, 3.0, 1.0])
    self.x = rdirichlet(alpha / numpy.sum(alpha))
    numpy.random.set_state(rstate) # Restore the backup state.
Esempio n. 21
0
    def test_3d(self, block):
        a000 = np.ones((2, 2, 2), int) * 1

        a100 = np.ones((3, 2, 2), int) * 2
        a010 = np.ones((2, 3, 2), int) * 3
        a001 = np.ones((2, 2, 3), int) * 4

        a011 = np.ones((2, 3, 3), int) * 5
        a101 = np.ones((3, 2, 3), int) * 6
        a110 = np.ones((3, 3, 2), int) * 7

        a111 = np.ones((3, 3, 3), int) * 8

        result = block([
            [
                [a000, a001],
                [a010, a011],
            ],
            [
                [a100, a101],
                [a110, a111],
            ]
        ])
        expected = array([[[1, 1, 4, 4, 4],
                           [1, 1, 4, 4, 4],
                           [3, 3, 5, 5, 5],
                           [3, 3, 5, 5, 5],
                           [3, 3, 5, 5, 5]],

                          [[1, 1, 4, 4, 4],
                           [1, 1, 4, 4, 4],
                           [3, 3, 5, 5, 5],
                           [3, 3, 5, 5, 5],
                           [3, 3, 5, 5, 5]],

                          [[2, 2, 6, 6, 6],
                           [2, 2, 6, 6, 6],
                           [7, 7, 8, 8, 8],
                           [7, 7, 8, 8, 8],
                           [7, 7, 8, 8, 8]],

                          [[2, 2, 6, 6, 6],
                           [2, 2, 6, 6, 6],
                           [7, 7, 8, 8, 8],
                           [7, 7, 8, 8, 8],
                           [7, 7, 8, 8, 8]],

                          [[2, 2, 6, 6, 6],
                           [2, 2, 6, 6, 6],
                           [7, 7, 8, 8, 8],
                           [7, 7, 8, 8, 8],
                           [7, 7, 8, 8, 8]]])

        assert_array_equal(result, expected)
Esempio n. 22
0
    def test_concatenate(self):
        # Test concatenate function
        # One sequence returns unmodified (but as array)
        r4 = list(range(4))
        assert_array_equal(concatenate((r4,)), r4)
        # Any sequence
        assert_array_equal(concatenate((tuple(r4),)), r4)
        assert_array_equal(concatenate((array(r4),)), r4)
        # 1D default concatenation
        r3 = list(range(3))
        assert_array_equal(concatenate((r4, r3)), r4 + r3)
        # Mixed sequence types
        assert_array_equal(concatenate((tuple(r4), r3)), r4 + r3)
        assert_array_equal(concatenate((array(r4), r3)), r4 + r3)
        # Explicit axis specification
        assert_array_equal(concatenate((r4, r3), 0), r4 + r3)
        # Including negative
        assert_array_equal(concatenate((r4, r3), -1), r4 + r3)
        # 2D
        a23 = array([[10, 11, 12], [13, 14, 15]])
        a13 = array([[0, 1, 2]])
        res = array([[10, 11, 12], [13, 14, 15], [0, 1, 2]])
        assert_array_equal(concatenate((a23, a13)), res)
        assert_array_equal(concatenate((a23, a13), 0), res)
        assert_array_equal(concatenate((a23.T, a13.T), 1), res.T)
        assert_array_equal(concatenate((a23.T, a13.T), -1), res.T)
        # Arrays much match shape
        assert_raises(ValueError, concatenate, (a23.T, a13.T), 0)
        # 3D
        res = arange(2 * 3 * 7).reshape((2, 3, 7))
        a0 = res[..., :4]
        a1 = res[..., 4:6]
        a2 = res[..., 6:]
        assert_array_equal(concatenate((a0, a1, a2), 2), res)
        assert_array_equal(concatenate((a0, a1, a2), -1), res)
        assert_array_equal(concatenate((a0.T, a1.T, a2.T), 0), res.T)

        out = res.copy()
        rout = concatenate((a0, a1, a2), 2, out=out)
        assert_(out is rout)
        assert_equal(res, rout)
Esempio n. 23
0
def ihfft(a, n=None, axis=-1):
    """
    Compute the inverse FFT of a signal which has Hermitian symmetry.

    Parameters
    ----------
    a : array_like
        Input array.
    n : int, optional
        Length of the inverse FFT.
        Number of points along transformation axis in the input to use.
        If `n` is smaller than the length of the input, the input is cropped.
        If it is larger, the input is padded with zeros. If `n` is not given,
        the length of the input along the axis specified by `axis` is used.
    axis : int, optional
        Axis over which to compute the inverse FFT. If not given, the last
        axis is used.

    Returns
    -------
    out : complex ndarray
        The truncated or zero-padded input, transformed along the axis
        indicated by `axis`, or the last one if `axis` is not specified.
        If `n` is even, the length of the transformed axis is ``(n/2)+1``.
        If `n` is odd, the length is ``(n+1)/2``.

    See also
    --------
    hfft, irfft

    Notes
    -----
    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
    opposite case: here the signal has Hermitian symmetry in the time domain
    and is real in the frequency domain. So here it's `hfft` for which
    you must supply the length of the result if it is to be odd:
    ``ihfft(hfft(a), len(a)) == a``, within numerical accuracy.

    Examples
    --------
    >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
    >>> np.fft.ifft(spectrum)
    array([ 1.+0.j,  2.-0.j,  3.+0.j,  4.+0.j,  3.+0.j,  2.-0.j])
    >>> np.fft.ihfft(spectrum)
    array([ 1.-0.j,  2.-0.j,  3.-0.j,  4.-0.j])

    """
    # The copy may be required for multithreading.
    a = array(a, copy=True, dtype=float)
    if n is None:
        n = shape(a)[axis]
    return conjugate(rfft(a, n, axis))/n
Esempio n. 24
0
 def test_concatenate_axis_None(self):
     a = np.arange(4, dtype=np.float64).reshape((2, 2))
     b = list(range(3))
     c = ['x']
     r = np.concatenate((a, a), axis=None)
     assert_equal(r.dtype, a.dtype)
     assert_equal(r.ndim, 1)
     r = np.concatenate((a, b), axis=None)
     assert_equal(r.size, a.size + len(b))
     assert_equal(r.dtype, a.dtype)
     r = np.concatenate((a, b, c), axis=None)
     d = array(['0.0', '1.0', '2.0', '3.0',
                '0', '1', '2', 'x'])
     assert_array_equal(r, d)
Esempio n. 25
0
def test_concatenate_axis_None():
    a = arange(4, dtype=float64).reshape((2,2))
    b = range(3)
    c = ['x']
    r = concatenate((a, a), axis=None)
    assert_equal(r.dtype, a.dtype)
    assert_equal(r.ndim, 1)
    r = concatenate((a, b), axis=None)
    assert_equal(r.size, a.size + len(b))
    assert_equal(r.dtype, a.dtype)
    r = concatenate((a, b, c), axis=None)
    d = array(['0', '1', '2', '3', 
               '0', '1', '2', 'x'])
    assert_array_equal(r,d)
Esempio n. 26
0
def clean_cr(raw, gain=0, mask=None, iterations=4)->array:
    """
    :param raw: 2-D array with image pixels
    :param mask: pre-loaded bad pixels/cr mask
    :param iterations: iterations to run
    :param gain: image gain value
    :return: a clean array and the calculated mask
    """
    if gain is None:
        gain = 0

    img = CosmicsImage(raw, gain=gain)
    img.clean(mask=mask)
    img.run(maxiter=iterations)

    return array(img.cleanarray), img.getmask()
Esempio n. 27
0
    def test_out_dtype(self):
        out = np.empty(4, np.float32)
        res = concatenate((array([1, 2]), array([3, 4])), out=out)
        assert_(out is res)

        out = np.empty(4, np.complex64)
        res = concatenate((array([0.1, 0.2]), array([0.3, 0.4])), out=out)
        assert_(out is res)

        # invalid cast
        out = np.empty(4, np.int32)
        assert_raises(TypeError, concatenate,
            (array([0.1, 0.2]), array([0.3, 0.4])), out=out)
Esempio n. 28
0
 def test_2D_array(self):
     a = array([[1],[2]]); b = array([[1],[2]]);
     res=vstack([a,b])
     desired = array([[1],[2],[1],[2]])
     assert_array_equal(res,desired)
Esempio n. 29
0
 def test_0D_array(self):
     a = array(1); b = array(2);
     res=map(atleast_1d,[a,b])
     desired = [array([1]),array([2])]
     assert_array_equal(res,desired)
Esempio n. 30
0
def coarseMolSurface(molFrag,
                     XYZd,
                     isovalue=5.0,
                     resolution=-0.4,
                     padding=0.0,
                     name='CoarseMolSurface',
                     geom=None):
    """
	Function adapted from the Vision network which compute a coarse molecular
	surface in PMV

	@type  molFrag: MolKit.AtomSet
	@param molFrag: the atoms selection
	@type  XYZd: array
	@param XYZd: shape of the volume
	@type  isovalue: float
	@param isovalue: isovalue for the isosurface computation
	@type  resolution: float
	@param resolution: resolution of the final mesh
	@type  padding: float
	@param padding: the padding
	@type  name: string
	@param name: the name of the resultante geometry
	@type  geom: DejaVu.Geom
	@param geom: update geom instead of creating a new one

	@rtype:   DejaVu.Geom
	@return:  the created or updated DejaVu.Geom
	"""
    import pdb
    from MolKit.molecule import Atom
    atoms = molFrag.findType(Atom)
    coords = atoms.coords
    radii = atoms.vdwRadius
    from UTpackages.UTblur import blur
    import numpy.core as Numeric

    volarr, origin, span = blur.generateBlurmap(coords,
                                                radii,
                                                XYZd,
                                                resolution,
                                                padding=0.0)
    volarr.shape = (XYZd[0], XYZd[1], XYZd[2])
    volarr = Numeric.ascontiguousarray(Numeric.transpose(volarr), 'f')

    weights = Numeric.ones(len(radii), 'f')
    h = {}
    from Volume.Grid3D import Grid3DF
    maskGrid = Grid3DF(volarr, origin, span, h)
    h['amin'], h['amax'], h['amean'], h['arms'] = maskGrid.stats()

    from UTpackages.UTisocontour import isocontour
    isocontour.setVerboseLevel(0)

    data = maskGrid.data

    origin = Numeric.array(maskGrid.origin).astype('f')
    stepsize = Numeric.array(maskGrid.stepSize).astype('f')

    if data.dtype.char != Numeric.float32:
        data = data.astype('f')  #Numeric.Float32)

    newgrid3D = Numeric.ascontiguousarray(
        Numeric.reshape(Numeric.transpose(data), (1, 1) + tuple(data.shape)),
        data.dtype.char)

    ndata = isocontour.newDatasetRegFloat3D(newgrid3D, origin, stepsize)

    isoc = isocontour.getContour3d(ndata, 0, 0, isovalue,
                                   isocontour.NO_COLOR_VARIABLE)
    vert = Numeric.zeros((isoc.nvert, 3)).astype('f')
    norm = Numeric.zeros((isoc.nvert, 3)).astype('f')
    col = Numeric.zeros((isoc.nvert)).astype('f')
    tri = Numeric.zeros((isoc.ntri, 3)).astype('i')

    isocontour.getContour3dData(isoc, vert, norm, col, tri, 0)

    if maskGrid.crystal:
        vert = maskGrid.crystal.toCartesian(vert)

    return (vert, tri)
Esempio n. 31
0
def eig(a):
    """
    Compute eigenvalues and right eigenvectors of an array.

    Parameters
    ----------
    a : array_like, shape (M, M)
        A complex or real 2-D array.

    Returns
    -------
    w : ndarray, shape (M,)
        The eigenvalues, each repeated according to its multiplicity.
        The eigenvalues are not necessarily ordered, nor are they
        necessarily real for real matrices.
    v : ndarray, shape (M, M)
        The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
        the column ``v[:,i]``.

    Raises
    ------
    LinAlgError
        If the eigenvalue computation does not converge.

    See Also
    --------
    eigvalsh : eigenvalues of symmetric or Hemitiean arrays.
    eig : eigenvalues and right eigenvectors for non-symmetric arrays
    eigvals : eigenvalues of non-symmetric array.

    Notes
    -----
    This is a simple interface to the LAPACK routines dgeev and zgeev
    that compute the eigenvalues and eigenvectors of general real and
    complex arrays respectively.

    The number `w` is an eigenvalue of a if there exists a vector `v`
    satisfying the equation ``dot(a,v) = w*v``. Alternately, if `w` is a root of
    the characteristic equation ``det(a - w[i]*I) = 0``, where `det` is the
    determinant and `I` is the identity matrix. The arrays `a`, `w`, and `v`
    satisfy the equation ``dot(a,v[i]) = w[i]*v[:,i]``.

    The array `v` of eigenvectors may not be of maximum rank, that is, some
    of the columns may be dependent, although roundoff error may obscure
    that fact. If the eigenvalues are all different, then theoretically the
    eigenvectors are independent. Likewise, the matrix of eigenvectors is
    unitary if the matrix `a` is normal, i.e., if ``dot(a, a.H) = dot(a.H, a)``.

    The left and right eigenvectors are not necessarily the (Hermitian)
    transposes of each other.

    """
    a, wrap = _makearray(a)
    _assertRank2(a)
    _assertSquareness(a)
    _assertFinite(a)
    a, t, result_t = _convertarray(a)  # convert to double or cdouble type
    real_t = _linalgRealType(t)
    n = a.shape[0]
    dummy = zeros((1, ), t)
    if isComplexType(t):
        # Complex routines take different arguments
        lapack_routine = lapack_lite.zgeev
        w = zeros((n, ), t)
        v = zeros((n, n), t)
        lwork = 1
        work = zeros((lwork, ), t)
        rwork = zeros((2 * n, ), real_t)
        results = lapack_routine('N', 'V', n, a, n, w, dummy, 1, v, n, work,
                                 -1, rwork, 0)
        lwork = int(abs(work[0]))
        work = zeros((lwork, ), t)
        results = lapack_routine('N', 'V', n, a, n, w, dummy, 1, v, n, work,
                                 lwork, rwork, 0)
    else:
        lapack_routine = lapack_lite.dgeev
        wr = zeros((n, ), t)
        wi = zeros((n, ), t)
        vr = zeros((n, n), t)
        lwork = 1
        work = zeros((lwork, ), t)
        results = lapack_routine('N', 'V', n, a, n, wr, wi, dummy, 1, vr, n,
                                 work, -1, 0)
        lwork = int(work[0])
        work = zeros((lwork, ), t)
        results = lapack_routine('N', 'V', n, a, n, wr, wi, dummy, 1, vr, n,
                                 work, lwork, 0)
        if all(wi == 0.0):
            w = wr
            v = vr
            result_t = _realType(result_t)
        else:
            w = wr + 1j * wi
            v = array(vr, w.dtype)
            ind = flatnonzero(wi != 0.0)  # indices of complex e-vals
            for i in range(len(ind) / 2):
                v[ind[2 * i]] = vr[ind[2 * i]] + 1j * vr[ind[2 * i + 1]]
                v[ind[2 * i + 1]] = vr[ind[2 * i]] - 1j * vr[ind[2 * i + 1]]
            result_t = _complexType(result_t)

    if results['info'] > 0:
        raise LinAlgError, 'Eigenvalues did not converge'
    vt = v.transpose().astype(result_t)
    return w.astype(result_t), wrap(vt)
Esempio n. 32
0
def lstsq(a, b, rcond=-1):
    """returns x,resids,rank,s
    where x minimizes 2-norm(|b - Ax|)
    resids is the sum square residuals
    rank is the rank of A
    s is the rank of the singular values of A in descending order

    If b is a matrix then x is also a matrix with corresponding columns.
    If the rank of A is less than the number of columns of A or greater than
    the number of rows, then residuals will be returned as an empty array
    otherwise resids = sum((b-dot(A,x)**2).
    Singular values less than s[0]*rcond are treated as zero.
"""
    import math
    a = asarray(a)
    b, wrap = _makearray(b)
    one_eq = len(b.shape) == 1
    if one_eq:
        b = b[:, newaxis]
    _assertRank2(a, b)
    m = a.shape[0]
    n = a.shape[1]
    n_rhs = b.shape[1]
    ldb = max(n, m)
    if m != b.shape[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t, result_t = _commonType(a, b)
    real_t = _linalgRealType(t)
    bstar = zeros((ldb, n_rhs), t)
    bstar[:b.shape[0], :n_rhs] = b.copy()
    a, bstar = _fastCopyAndTranspose(t, a, bstar)
    s = zeros((min(m, n), ), real_t)
    nlvl = max(0, int(math.log(float(min(m, n)) / 2.)) + 1)
    iwork = zeros((3 * min(m, n) * nlvl + 11 * min(m, n), ), fortran_int)
    if isComplexType(t):
        lapack_routine = lapack_lite.zgelsd
        lwork = 1
        rwork = zeros((lwork, ), real_t)
        work = zeros((lwork, ), t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0,
                                 work, -1, rwork, iwork, 0)
        lwork = int(abs(work[0]))
        rwork = zeros((lwork, ), real_t)
        a_real = zeros((m, n), real_t)
        bstar_real = zeros((
            ldb,
            n_rhs,
        ), real_t)
        results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m, bstar_real, ldb,
                                     s, rcond, 0, rwork, -1, iwork, 0)
        lrwork = int(rwork[0])
        work = zeros((lwork, ), t)
        rwork = zeros((lrwork, ), real_t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0,
                                 work, lwork, rwork, iwork, 0)
    else:
        lapack_routine = lapack_lite.dgelsd
        lwork = 1
        work = zeros((lwork, ), t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0,
                                 work, -1, iwork, 0)
        lwork = int(work[0])
        work = zeros((lwork, ), t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0,
                                 work, lwork, iwork, 0)
    if results['info'] > 0:
        raise LinAlgError, 'SVD did not converge in Linear Least Squares'
    resids = array([], t)
    if one_eq:
        x = array(ravel(bstar)[:n], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_t)
    else:
        x = array(transpose(bstar)[:n, :], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = sum((transpose(bstar)[n:, :])**2, axis=0).astype(result_t)
    st = s[:min(n, m)].copy().astype(_realType(result_t))
    return wrap(x), resids, results['rank'], st
Esempio n. 33
0
 def test_2D_array2(self):
     a = array([1, 2])
     b = array([1, 2])
     res = vstack([a, b])
     desired = array([[1, 2], [1, 2]])
     assert_array_equal(res, desired)
Esempio n. 34
0
 def test_1D_array(self):
     a = array([1])
     b = array([2])
     res = vstack([a, b])
     desired = array([[1], [2]])
     assert_array_equal(res, desired)
Esempio n. 35
0
def assert_array_compare(comparison, x, y, err_msg='', verbose=True,
                         header=''):
    from numpy.core import array, isnan, any
    x = array(x, copy=False, subok=True)
    y = array(y, copy=False, subok=True)

    def isnumber(x):
        return x.dtype.char in '?bhilqpBHILQPfdgFDG'

    try:
        cond = (x.shape==() or y.shape==()) or x.shape == y.shape
        if not cond:
            msg = build_err_msg([x, y],
                                err_msg
                                + '\n(shapes %s, %s mismatch)' % (x.shape,
                                                                  y.shape),
                                verbose=verbose, header=header,
                                names=('x', 'y'))
            if not cond :
                raise AssertionError(msg)

        if (isnumber(x) and isnumber(y)) and (any(isnan(x)) or any(isnan(y))):
            # Handling nan: we first check that x and y have the nan at the
            # same locations, and then we mask the nan and do the comparison as
            # usual.
            xnanid = isnan(x)
            ynanid = isnan(y)
            try:
                assert_array_equal(xnanid, ynanid)
            except AssertionError:
                msg = build_err_msg([x, y],
                                    err_msg
                                    + '\n(x and y nan location mismatch %s, ' \
                                    '%s mismatch)' % (xnanid, ynanid),
                                    verbose=verbose, header=header,
                                    names=('x', 'y'))
                raise AssertionError(msg)
            # If only one item, it was a nan, so just return
            if x.size == y.size == 1:
                return
            val = comparison(x[~xnanid], y[~ynanid])
        else:
            val = comparison(x,y)
        if isinstance(val, bool):
            cond = val
            reduced = [0]
        else:
            reduced = val.ravel()
            cond = reduced.all()
            reduced = reduced.tolist()
        if not cond:
            match = 100-100.0*reduced.count(1)/len(reduced)
            msg = build_err_msg([x, y],
                                err_msg
                                + '\n(mismatch %s%%)' % (match,),
                                verbose=verbose, header=header,
                                names=('x', 'y'))
            if not cond :
                raise AssertionError(msg)
    except ValueError:
        msg = build_err_msg([x, y], err_msg, verbose=verbose, header=header,
                            names=('x', 'y'))
        raise ValueError(msg)
Esempio n. 36
0
def eig(a):
    """
    Compute eigenvalues and right eigenvectors of an array.

    Parameters
    ----------
    a : array_like, shape (M, M)
        A complex or real 2-D array.

    Returns
    -------
    w : ndarray, shape (M,)
        The eigenvalues, each repeated according to its multiplicity.
        The eigenvalues are not necessarily ordered, nor are they
        necessarily real for real matrices.
    v : ndarray, shape (M, M)
        The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
        the column ``v[:,i]``.

    Raises
    ------
    LinAlgError
        If the eigenvalue computation does not converge.

    See Also
    --------
    eigvalsh : eigenvalues of symmetric or Hemitiean arrays.
    eig : eigenvalues and right eigenvectors for non-symmetric arrays
    eigvals : eigenvalues of non-symmetric array.

    Notes
    -----
    This is a simple interface to the LAPACK routines dgeev and zgeev
    that compute the eigenvalues and eigenvectors of general real and
    complex arrays respectively.

    The number `w` is an eigenvalue of a if there exists a vector `v`
    satisfying the equation ``dot(a,v) = w*v``. Alternately, if `w` is
    a root of the characteristic equation ``det(a - w[i]*I) = 0``, where
    `det` is the determinant and `I` is the identity matrix. The arrays
    `a`, `w`, and `v` satisfy the equation ``dot(a,v[i]) = w[i]*v[:,i]``.

    The array `v` of eigenvectors may not be of maximum rank, that is, some
    of the columns may be dependent, although roundoff error may
    obscure that fact. If the eigenvalues are all different, then theoretically
    the eigenvectors are independent. Likewise, the matrix of eigenvectors
    is unitary if the matrix `a` is normal, i.e., if
    ``dot(a, a.H) = dot(a.H, a)``.

    The left and right eigenvectors are not necessarily the (Hermitian)
    transposes of each other.

    """
    a, wrap = _makearray(a)
    _assertRank2(a)
    _assertSquareness(a)
    _assertFinite(a)
    a, t, result_t = _convertarray(a) # convert to double or cdouble type
    real_t = _linalgRealType(t)
    n = a.shape[0]
    dummy = zeros((1,), t)
    if isComplexType(t):
        # Complex routines take different arguments
        lapack_routine = lapack_lite.zgeev
        w = zeros((n,), t)
        v = zeros((n, n), t)
        lwork = 1
        work = zeros((lwork,), t)
        rwork = zeros((2*n,), real_t)
        results = lapack_routine('N', 'V', n, a, n, w,
                                 dummy, 1, v, n, work, -1, rwork, 0)
        lwork = int(abs(work[0]))
        work = zeros((lwork,), t)
        results = lapack_routine('N', 'V', n, a, n, w,
                                 dummy, 1, v, n, work, lwork, rwork, 0)
    else:
        lapack_routine = lapack_lite.dgeev
        wr = zeros((n,), t)
        wi = zeros((n,), t)
        vr = zeros((n, n), t)
        lwork = 1
        work = zeros((lwork,), t)
        results = lapack_routine('N', 'V', n, a, n, wr, wi,
                                  dummy, 1, vr, n, work, -1, 0)
        lwork = int(work[0])
        work = zeros((lwork,), t)
        results = lapack_routine('N', 'V', n, a, n, wr, wi,
                                  dummy, 1, vr, n, work, lwork, 0)
        if all(wi == 0.0):
            w = wr
            v = vr
            result_t = _realType(result_t)
        else:
            w = wr+1j*wi
            v = array(vr, w.dtype)
            ind = flatnonzero(wi != 0.0)      # indices of complex e-vals
            for i in range(len(ind)/2):
                v[ind[2*i]] = vr[ind[2*i]] + 1j*vr[ind[2*i+1]]
                v[ind[2*i+1]] = vr[ind[2*i]] - 1j*vr[ind[2*i+1]]
            result_t = _complexType(result_t)

    if results['info'] > 0:
        raise LinAlgError, 'Eigenvalues did not converge'
    vt = v.transpose().astype(result_t)
    return w.astype(result_t), wrap(vt)
Esempio n. 37
0
 def __new__(cls, data, metadata=None):
     res = nx.array(data, copy=True).view(cls)
     res.metadata = metadata
     return res
Esempio n. 38
0
 def test_2D_array(self):
     a = array([[1, 2], [1, 2]])
     b = array([[2, 3], [2, 3]])
     res = [atleast_3d(a), atleast_3d(b)]
     desired = [a[:,:, newaxis], b[:,:, newaxis]]
     assert_array_equal(res, desired)
Esempio n. 39
0
def poly(seq_of_zeros):
    """
    Find the coefficients of a polynomial with the given sequence of roots.

    Returns the coefficients of the polynomial whose leading coefficient
    is one for the given sequence of zeros (multiple roots must be included
    in the sequence as many times as their multiplicity; see Examples).
    A square matrix (or array, which will be treated as a matrix) can also
    be given, in which case the coefficients of the characteristic polynomial
    of the matrix are returned.

    Parameters
    ----------
    seq_of_zeros : array_like, shape (N,) or (N, N)
        A sequence of polynomial roots, or a square array or matrix object.

    Returns
    -------
    c : ndarray
        1D array of polynomial coefficients from highest to lowest degree:

        ``c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N]``
        where c[0] always equals 1.

    Raises
    ------
    ValueError
        If input is the wrong shape (the input must be a 1-D or square
        2-D array).

    See Also
    --------
    polyval : Compute polynomial values.
    roots : Return the roots of a polynomial.
    polyfit : Least squares polynomial fit.
    poly1d : A one-dimensional polynomial class.

    Notes
    -----
    Specifying the roots of a polynomial still leaves one degree of
    freedom, typically represented by an undetermined leading
    coefficient. [1]_ In the case of this function, that coefficient -
    the first one in the returned array - is always taken as one. (If
    for some reason you have one other point, the only automatic way
    presently to leverage that information is to use ``polyfit``.)

    The characteristic polynomial, :math:`p_a(t)`, of an `n`-by-`n`
    matrix **A** is given by

        :math:`p_a(t) = \\mathrm{det}(t\\, \\mathbf{I} - \\mathbf{A})`,

    where **I** is the `n`-by-`n` identity matrix. [2]_

    References
    ----------
    .. [1] M. Sullivan and M. Sullivan, III, "Algebra and Trignometry,
       Enhanced With Graphing Utilities," Prentice-Hall, pg. 318, 1996.

    .. [2] G. Strang, "Linear Algebra and Its Applications, 2nd Edition,"
       Academic Press, pg. 182, 1980.

    Examples
    --------
    Given a sequence of a polynomial's zeros:

    >>> np.poly((0, 0, 0)) # Multiple root example
    array([1., 0., 0., 0.])

    The line above represents z**3 + 0*z**2 + 0*z + 0.

    >>> np.poly((-1./2, 0, 1./2))
    array([ 1.  ,  0.  , -0.25,  0.  ])

    The line above represents z**3 - z/4

    >>> np.poly((np.random.random(1)[0], 0, np.random.random(1)[0]))
    array([ 1.        , -0.77086955,  0.08618131,  0.        ]) # random

    Given a square array object:

    >>> P = np.array([[0, 1./3], [-1./2, 0]])
    >>> np.poly(P)
    array([1.        , 0.        , 0.16666667])

    Note how in all cases the leading coefficient is always 1.

    """
    seq_of_zeros = atleast_1d(seq_of_zeros)
    sh = seq_of_zeros.shape

    if len(sh) == 2 and sh[0] == sh[1] and sh[0] != 0:
        seq_of_zeros = eigvals(seq_of_zeros)
    elif len(sh) == 1:
        dt = seq_of_zeros.dtype
        # Let object arrays slip through, e.g. for arbitrary precision
        if dt != object:
            seq_of_zeros = seq_of_zeros.astype(mintypecode(dt.char))
    else:
        raise ValueError("input must be 1d or non-empty square 2d array.")

    if len(seq_of_zeros) == 0:
        return 1.0
    dt = seq_of_zeros.dtype
    a = ones((1, ), dtype=dt)
    for k in range(len(seq_of_zeros)):
        a = NX.convolve(a, array([1, -seq_of_zeros[k]], dtype=dt), mode='full')

    if issubclass(a.dtype.type, NX.complexfloating):
        # if complex roots are all complex conjugates, the roots are real.
        roots = NX.asarray(seq_of_zeros, complex)
        if NX.all(NX.sort(roots) == NX.sort(roots.conjugate())):
            a = a.real.copy()

    return a
Esempio n. 40
0
def test_stack():
    # non-iterable input
    assert_raises(TypeError, stack, 1)

    # 0d input
    for input_ in [(1, 2, 3), [np.int32(1),
                               np.int32(2),
                               np.int32(3)],
                   [np.array(1), np.array(2),
                    np.array(3)]]:
        assert_array_equal(stack(input_), [1, 2, 3])
    # 1d input examples
    a = np.array([1, 2, 3])
    b = np.array([4, 5, 6])
    r1 = array([[1, 2, 3], [4, 5, 6]])
    assert_array_equal(np.stack((a, b)), r1)
    assert_array_equal(np.stack((a, b), axis=1), r1.T)
    # all input types
    assert_array_equal(np.stack(list([a, b])), r1)
    assert_array_equal(np.stack(array([a, b])), r1)
    # all shapes for 1d input
    arrays = [np.random.randn(3) for _ in range(10)]
    axes = [0, 1, -1, -2]
    expected_shapes = [(10, 3), (3, 10), (3, 10), (10, 3)]
    for axis, expected_shape in zip(axes, expected_shapes):
        assert_equal(np.stack(arrays, axis).shape, expected_shape)
    assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=2)
    assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=-3)
    # all shapes for 2d input
    arrays = [np.random.randn(3, 4) for _ in range(10)]
    axes = [0, 1, 2, -1, -2, -3]
    expected_shapes = [(10, 3, 4), (3, 10, 4), (3, 4, 10), (3, 4, 10),
                       (3, 10, 4), (10, 3, 4)]
    for axis, expected_shape in zip(axes, expected_shapes):
        assert_equal(np.stack(arrays, axis).shape, expected_shape)
    # empty arrays
    assert_(stack([[], [], []]).shape == (3, 0))
    assert_(stack([[], [], []], axis=1).shape == (0, 3))
    # out
    out = np.zeros_like(r1)
    np.stack((a, b), out=out)
    assert_array_equal(out, r1)
    # edge cases
    assert_raises_regex(ValueError, 'need at least one array', stack, [])
    assert_raises_regex(ValueError, 'must have the same shape', stack,
                        [1, np.arange(3)])
    assert_raises_regex(ValueError, 'must have the same shape', stack,
                        [np.arange(3), 1])
    assert_raises_regex(ValueError,
                        'must have the same shape',
                        stack, [np.arange(3), 1],
                        axis=1)
    assert_raises_regex(ValueError,
                        'must have the same shape',
                        stack, [np.zeros(
                            (3, 3)), np.zeros(3)],
                        axis=1)
    assert_raises_regex(ValueError, 'must have the same shape', stack,
                        [np.arange(2), np.arange(3)])
    # generator is deprecated
    with assert_warns(FutureWarning):
        result = stack((x for x in range(3)))
    assert_array_equal(result, np.array([0, 1, 2]))
Esempio n. 41
0
 def test_2D_array(self):
     a = array([[1, 2], [1, 2]])
     b = array([[2, 3], [2, 3]])
     res = map(atleast_3d, [a, b])
     desired = [a[:, :, newaxis], b[:, :, newaxis]]
     assert_array_equal(res, desired)
Esempio n. 42
0
 def test_1D_array(self):
     a = array([1, 2])
     b = array([2, 3])
     res = [atleast_1d(a), atleast_1d(b)]
     desired = [array([1, 2]), array([2, 3])]
     assert_array_equal(res, desired)
Esempio n. 43
0
def eig(a):
    """Eigenvalues and right eigenvectors of a general matrix.

    A simple interface to the LAPACK routines dgeev and zgeev that compute the
    eigenvalues and eigenvectors of general real and complex arrays
    respectively.

    :Parameters:

        a : 2-d array
            A complex or real 2-d array whose eigenvalues and eigenvectors
            will be computed.

    :Returns:

        w : 1-d double or complex array
            The eigenvalues. The eigenvalues are not necessarily ordered, nor
            are they necessarily real for real matrices.

        v : 2-d double or complex double array.
            The normalized eigenvector corresponding to the eigenvalue w[i] is
            the column v[:,i].

    :SeeAlso:

        - eigvalsh : eigenvalues of symmetric or Hemitiean arrays.
        - eig : eigenvalues and right eigenvectors for non-symmetric arrays
        - eigvals : eigenvalues of non-symmetric array.

    :Notes:
    -------

        The number w is an eigenvalue of a if there exists a vector v
        satisfying the equation dot(a,v) = w*v. Alternately, if w is a root of
        the characteristic equation det(a - w[i]*I) = 0, where det is the
        determinant and I is the identity matrix. The arrays a, w, and v
        satisfy the equation dot(a,v[i]) = w[i]*v[:,i].

        The array v of eigenvectors may not be of maximum rank, that is, some
        of the columns may be dependent, although roundoff error may obscure
        that fact. If the eigenvalues are all different, then theoretically the
        eigenvectors are independent. Likewise, the matrix of eigenvectors is
        unitary if the matrix a is normal, i.e., if dot(a, a.H) = dot(a.H, a).

        The left and right eigenvectors are not necessarily the (Hemitian)
        transposes of each other.

    """
    a, wrap = _makearray(a)
    _assertRank2(a)
    _assertSquareness(a)
    _assertFinite(a)
    a, t, result_t = _convertarray(a)  # convert to double or cdouble type
    real_t = _linalgRealType(t)
    n = a.shape[0]
    dummy = zeros((1, ), t)
    if isComplexType(t):
        # Complex routines take different arguments
        lapack_routine = lapack_lite.zgeev
        w = zeros((n, ), t)
        v = zeros((n, n), t)
        lwork = 1
        work = zeros((lwork, ), t)
        rwork = zeros((2 * n, ), real_t)
        results = lapack_routine('N', 'V', n, a, n, w, dummy, 1, v, n, work,
                                 -1, rwork, 0)
        lwork = int(abs(work[0]))
        work = zeros((lwork, ), t)
        results = lapack_routine('N', 'V', n, a, n, w, dummy, 1, v, n, work,
                                 lwork, rwork, 0)
    else:
        lapack_routine = lapack_lite.dgeev
        wr = zeros((n, ), t)
        wi = zeros((n, ), t)
        vr = zeros((n, n), t)
        lwork = 1
        work = zeros((lwork, ), t)
        results = lapack_routine('N', 'V', n, a, n, wr, wi, dummy, 1, vr, n,
                                 work, -1, 0)
        lwork = int(work[0])
        work = zeros((lwork, ), t)
        results = lapack_routine('N', 'V', n, a, n, wr, wi, dummy, 1, vr, n,
                                 work, lwork, 0)
        if all(wi == 0.0):
            w = wr
            v = vr
            result_t = _realType(result_t)
        else:
            w = wr + 1j * wi
            v = array(vr, w.dtype)
            ind = flatnonzero(wi != 0.0)  # indices of complex e-vals
            for i in range(len(ind) / 2):
                v[ind[2 * i]] = vr[ind[2 * i]] + 1j * vr[ind[2 * i + 1]]
                v[ind[2 * i + 1]] = vr[ind[2 * i]] - 1j * vr[ind[2 * i + 1]]
            result_t = _complexType(result_t)

    if results['info'] > 0:
        raise LinAlgError, 'Eigenvalues did not converge'
    vt = v.transpose().astype(result_t)
    return w.astype(result_t), wrap(vt)
Esempio n. 44
0
 def test_2D_array(self):
     a = array([[1, 2], [1, 2]])
     b = array([[2, 3], [2, 3]])
     res = [atleast_1d(a), atleast_1d(b)]
     desired = [a, b]
     assert_array_equal(res, desired)
Esempio n. 45
0
def lstsq(a, b, rcond=-1):
    """
    Return the least-squares solution to an equation.

    Solves the equation `a x = b` by computing a vector `x` that minimizes
    the norm `|| b - a x ||`.

    Parameters
    ----------
    a : array_like, shape (M, N)
        Input equation coefficients.
    b : array_like, shape (M,) or (M, K)
        Equation target values.  If `b` is two-dimensional, the least
        squares solution is calculated for each of the `K` target sets.
    rcond : float, optional
        Cutoff for ``small`` singular values of `a`.
        Singular values smaller than `rcond` times the largest singular
        value are  considered zero.

    Returns
    -------
    x : ndarray, shape(N,) or (N, K)
         Least squares solution.  The shape of `x` depends on the shape of
         `b`.
    residues : ndarray, shape(), (1,), or (K,)
        Sums of residues; squared Euclidian norm for each column in
        `b - a x`.
        If the rank of `a` is < N or > M, this is an empty array.
        If `b` is 1-dimensional, this is a (1,) shape array.
        Otherwise the shape is (K,).
    rank : integer
        Rank of matrix `a`.
    s : ndarray, shape(min(M,N),)
        Singular values of `a`.

    Raises
    ------
    LinAlgError
        If computation does not converge.

    Notes
    -----
    If `b` is a matrix, then all array results returned as
    matrices.

    Examples
    --------
    Fit a line, ``y = mx + c``, through some noisy data-points:

    >>> x = np.array([0, 1, 2, 3])
    >>> y = np.array([-1, 0.2, 0.9, 2.1])

    By examining the coefficients, we see that the line should have a
    gradient of roughly 1 and cuts the y-axis at more-or-less -1.

    We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
    and ``p = [[m], [c]]``.  Now use `lstsq` to solve for `p`:

    >>> A = np.vstack([x, np.ones(len(x))]).T
    >>> A
    array([[ 0.,  1.],
           [ 1.,  1.],
           [ 2.,  1.],
           [ 3.,  1.]])

    >>> m, c = np.linalg.lstsq(A, y)[0]
    >>> print m, c
    1.0 -0.95

    Plot the data along with the fitted line:

    >>> import matplotlib.pyplot as plt
    >>> plt.plot(x, y, 'o', label='Original data', markersize=10)
    >>> plt.plot(x, m*x + c, 'r', label='Fitted line')
    >>> plt.legend()
    >>> plt.show()

    """
    import math
    a, _ = _makearray(a)
    b, wrap = _makearray(b)
    is_1d = len(b.shape) == 1
    if is_1d:
        b = b[:, newaxis]
    _assertRank2(a, b)
    m = a.shape[0]
    n = a.shape[1]
    n_rhs = b.shape[1]
    ldb = max(n, m)
    if m != b.shape[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t, result_t = _commonType(a, b)
    real_t = _linalgRealType(t)
    bstar = zeros((ldb, n_rhs), t)
    bstar[:b.shape[0], :n_rhs] = b.copy()
    a, bstar = _fastCopyAndTranspose(t, a, bstar)
    s = zeros((min(m, n), ), real_t)
    nlvl = max(0, int(math.log(float(min(m, n)) / 2.)) + 1)
    iwork = zeros((3 * min(m, n) * nlvl + 11 * min(m, n), ), fortran_int)
    if isComplexType(t):
        lapack_routine = lapack_lite.zgelsd
        lwork = 1
        rwork = zeros((lwork, ), real_t)
        work = zeros((lwork, ), t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0,
                                 work, -1, rwork, iwork, 0)
        lwork = int(abs(work[0]))
        rwork = zeros((lwork, ), real_t)
        a_real = zeros((m, n), real_t)
        bstar_real = zeros((
            ldb,
            n_rhs,
        ), real_t)
        results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m, bstar_real, ldb,
                                     s, rcond, 0, rwork, -1, iwork, 0)
        lrwork = int(rwork[0])
        work = zeros((lwork, ), t)
        rwork = zeros((lrwork, ), real_t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0,
                                 work, lwork, rwork, iwork, 0)
    else:
        lapack_routine = lapack_lite.dgelsd
        lwork = 1
        work = zeros((lwork, ), t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0,
                                 work, -1, iwork, 0)
        lwork = int(work[0])
        work = zeros((lwork, ), t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0,
                                 work, lwork, iwork, 0)
    if results['info'] > 0:
        raise LinAlgError, 'SVD did not converge in Linear Least Squares'
    resids = array([], t)
    if is_1d:
        x = array(ravel(bstar)[:n], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_t)
    else:
        x = array(transpose(bstar)[:n, :], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = sum((transpose(bstar)[n:, :])**2, axis=0).astype(result_t)
    st = s[:min(n, m)].copy().astype(_realType(result_t))
    return wrap(x), wrap(resids), results['rank'], st
Esempio n. 46
0
 def __init__(self, data, dtype=None, copy=True):
     self.array = array(data, dtype, copy=copy)
Esempio n. 47
0
def hfft(a, n=None, axis=-1, norm=None):
    """
    Compute the FFT of a signal which has Hermitian symmetry (real spectrum).

    Parameters
    ----------
    a : array_like
        The input array.
    n : int, optional
        Length of the transformed axis of the output.
        For `n` output points, ``n//2+1`` input points are necessary.  If the
        input is longer than this, it is cropped.  If it is shorter than this,
        it is padded with zeros.  If `n` is not given, it is determined from
        the length of the input along the axis specified by `axis`.
    axis : int, optional
        Axis over which to compute the FFT. If not given, the last
        axis is used.
    norm : {None, "ortho"}, optional
        .. versionadded:: 1.10.0
        Normalization mode (see `numpy.fft`). Default is None.

    Returns
    -------
    out : ndarray
        The truncated or zero-padded input, transformed along the axis
        indicated by `axis`, or the last one if `axis` is not specified.
        The length of the transformed axis is `n`, or, if `n` is not given,
        ``2*(m-1)`` where ``m`` is the length of the transformed axis of the
        input. To get an odd number of output points, `n` must be specified.

    Raises
    ------
    IndexError
        If `axis` is larger than the last axis of `a`.

    See also
    --------
    rfft : Compute the one-dimensional FFT for real input.
    ihfft : The inverse of `hfft`.

    Notes
    -----
    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
    opposite case: here the signal has Hermitian symmetry in the time domain
    and is real in the frequency domain. So here it's `hfft` for which
    you must supply the length of the result if it is to be odd:
    ``ihfft(hfft(a), len(a)) == a``, within numerical accuracy.

    Examples
    --------
    >>> signal = np.array([1, 2, 3, 4, 3, 2])
    >>> np.fft.fft(signal)
    array([ 15.+0.j,  -4.+0.j,   0.+0.j,  -1.-0.j,   0.+0.j,  -4.+0.j])
    >>> np.fft.hfft(signal[:4]) # Input first half of signal
    array([ 15.,  -4.,   0.,  -1.,   0.,  -4.])
    >>> np.fft.hfft(signal, 6)  # Input entire signal and truncate
    array([ 15.,  -4.,   0.,  -1.,   0.,  -4.])


    >>> signal = np.array([[1, 1.j], [-1.j, 2]])
    >>> np.conj(signal.T) - signal   # check Hermitian symmetry
    array([[ 0.-0.j,  0.+0.j],
           [ 0.+0.j,  0.-0.j]])
    >>> freq_spectrum = np.fft.hfft(signal)
    >>> freq_spectrum
    array([[ 1.,  1.],
           [ 2., -2.]])

    """
    x = _float_utils.__downcast_float128_array(a)
    x = array(x, copy=True, dtype=complex)
    if n is None:
        n = (x.shape[axis] - 1) * 2
    unitary = _unitary(norm)
    return irfft(conjugate(x), n, axis) * (sqrt(n) if unitary else n)
Esempio n. 48
0
    """Test both numpy and built-in complex."""
    coefs = [0 + 1j, 1 + 1j, -2 + 2j, 3 + 0j]
    # numpy complex
    p1 = poly.Polynomial(coefs)
    # Python complex
    p2 = poly.Polynomial(array(coefs, dtype=object))
    poly.set_default_printstyle('unicode')
    assert_equal(str(p1), "1j + (1+1j)·x¹ - (2-2j)·x² + (3+0j)·x³")
    assert_equal(str(p2), "1j + (1+1j)·x¹ + (-2+2j)·x² + (3+0j)·x³")
    poly.set_default_printstyle('ascii')
    assert_equal(str(p1), "1j + (1+1j) x**1 - (2-2j) x**2 + (3+0j) x**3")
    assert_equal(str(p2), "1j + (1+1j) x**1 + (-2+2j) x**2 + (3+0j) x**3")


@pytest.mark.parametrize(('coefs', 'tgt'), (
    (array([Fraction(1, 2), Fraction(3, 4)], dtype=object), ("1/2 + 3/4·x¹")),
    (array([1, 2, Fraction(5, 7)], dtype=object), ("1 + 2·x¹ + 5/7·x²")),
    (array([Decimal('1.00'), Decimal('2.2'), 3], dtype=object),
     ("1.00 + 2.2·x¹ + 3·x²")),
))
def test_numeric_object_coefficients(coefs, tgt):
    p = poly.Polynomial(coefs)
    poly.set_default_printstyle('unicode')
    assert_equal(str(p), tgt)


@pytest.mark.parametrize(('coefs', 'tgt'), (
    (array([1, 2, 'f'], dtype=object), '1 + 2·x¹ + f·x²'),
    (array([1, 2, [3, 4]], dtype=object), '1 + 2·x¹ + [3, 4]·x²'),
))
def test_nonnumeric_object_coefficients(coefs, tgt):
Esempio n. 49
0
def assert_array_compare(comparison, x, y, err_msg='', verbose=True,
                         header=''):
    from numpy.core import array, isnan, isinf, any, all, inf
    x = array(x, copy=False, subok=True)
    y = array(y, copy=False, subok=True)

    def isnumber(x):
        return x.dtype.char in '?bhilqpBHILQPefdgFDG'

    def chk_same_position(x_id, y_id, hasval='nan'):
        """Handling nan/inf: check that x and y have the nan/inf at the same
        locations."""
        try:
            assert_array_equal(x_id, y_id)
        except AssertionError:
            msg = build_err_msg([x, y],
                                err_msg + '\nx and y %s location mismatch:' \
                                % (hasval), verbose=verbose, header=header,
                                names=('x', 'y'))
            raise AssertionError(msg)

    try:
        cond = (x.shape==() or y.shape==()) or x.shape == y.shape
        if not cond:
            msg = build_err_msg([x, y],
                                err_msg
                                + '\n(shapes %s, %s mismatch)' % (x.shape,
                                                                  y.shape),
                                verbose=verbose, header=header,
                                names=('x', 'y'))
            if not cond :
                raise AssertionError(msg)

        if isnumber(x) and isnumber(y):
            x_isnan, y_isnan = isnan(x), isnan(y)
            x_isinf, y_isinf = isinf(x), isinf(y)

            # Validate that the special values are in the same place
            if any(x_isnan) or any(y_isnan):
                chk_same_position(x_isnan, y_isnan, hasval='nan')
            if any(x_isinf) or any(y_isinf):
                # Check +inf and -inf separately, since they are different
                chk_same_position(x == +inf, y == +inf, hasval='+inf')
                chk_same_position(x == -inf, y == -inf, hasval='-inf')

            # Combine all the special values
            x_id, y_id = x_isnan, y_isnan
            x_id |= x_isinf
            y_id |= y_isinf

            # Only do the comparison if actual values are left
            if all(x_id):
                return

            if any(x_id):
                val = comparison(x[~x_id], y[~y_id])
            else:
                val = comparison(x, y)
        else:
            val = comparison(x,y)

        if isinstance(val, bool):
            cond = val
            reduced = [0]
        else:
            reduced = val.ravel()
            cond = reduced.all()
            reduced = reduced.tolist()
        if not cond:
            match = 100-100.0*reduced.count(1)/len(reduced)
            msg = build_err_msg([x, y],
                                err_msg
                                + '\n(mismatch %s%%)' % (match,),
                                verbose=verbose, header=header,
                                names=('x', 'y'))
            if not cond :
                raise AssertionError(msg)
    except ValueError as e:
        import traceback
        efmt = traceback.format_exc()
        header = 'error during assertion:\n\n%s\n\n%s' % (efmt, header)

        msg = build_err_msg([x, y], err_msg, verbose=verbose, header=header,
                            names=('x', 'y'))
        raise ValueError(msg)
Esempio n. 50
0
 def test_1D_array(self):
     a = array([1, 2])
     b = array([2, 3])
     res = map(atleast_3d, [a, b])
     desired = [array([[[1], [2]]]), array([[[2], [3]]])]
     assert_array_equal(res, desired)
Esempio n. 51
0
 def test_3D_array(self):
     a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
     a = array([a,a]);b = array([b,b]);
     res=map(atleast_3d,[a,b])
     desired = [a,b]
     assert_array_equal(res,desired)
Esempio n. 52
0
 def test_0D_array(self):
     a = array(1)
     b = array(2)
     res = map(atleast_3d, [a, b])
     desired = [array([[[1]]]), array([[[2]]])]
     assert_array_equal(res, desired)
Esempio n. 53
0
 def test_1D_array(self):
     a = array([1,2]); b = array([2,3]);
     res=map(atleast_2d,[a,b])
     desired = [array([[1,2]]),array([[2,3]])]
     assert_array_equal(res,desired)
Esempio n. 54
0
 def test_2D_array(self):
     a = array([[1, 2], [1, 2]])
     b = array([[2, 3], [2, 3]])
     res = map(atleast_2d, [a, b])
     desired = [a, b]
     assert_array_equal(res, desired)
Esempio n. 55
0
 def test_0D_array(self):
     a = array(1)
     b = array(2)
     res = hstack([a, b])
     desired = array([1, 2])
     assert_array_equal(res, desired)
Esempio n. 56
0
 def buff_ptsalpha(points, alpha):
     return np.hstack((
         np.array([tuple(p) for p in points], 'f4'),
         np.array(alpha, 'f4', ndmin=2).transpose(),
     ))
Esempio n. 57
0
def lstsq(a, b, rcond=-1):
    """
    Return the least-squares solution to an equation.

    Solves the equation `a x = b` by computing a vector `x` that minimizes
    the norm `|| b - a x ||`.

    Parameters
    ----------
    a : array_like, shape (M, N)
        Input equation coefficients.
    b : array_like, shape (M,) or (M, K)
        Equation target values.  If `b` is two-dimensional, the least
        squares solution is calculated for each of the `K` target sets.
    rcond : float, optional
        Cutoff for ``small`` singular values of `a`.
        Singular values smaller than `rcond` times the largest singular
        value are  considered zero.

    Returns
    -------
    x : ndarray, shape(N,) or (N, K)
         Least squares solution.  The shape of `x` depends on the shape of
         `b`.
    residues : ndarray, shape(), (1,), or (K,)
        Sums of residues; squared Euclidian norm for each column in
        `b - a x`.
        If the rank of `a` is < N or > M, this is an empty array.
        If `b` is 1-dimensional, this is a (1,) shape array.
        Otherwise the shape is (K,).
    rank : integer
        Rank of matrix `a`.
    s : ndarray, shape(min(M,N),)
        Singular values of `a`.

    Raises
    ------
    LinAlgError
        If computation does not converge.

    Notes
    -----
    If `b` is a matrix, then all array results returned as
    matrices.

    Examples
    --------
    Fit a line, ``y = mx + c``, through some noisy data-points:

    >>> x = np.array([0, 1, 2, 3])
    >>> y = np.array([-1, 0.2, 0.9, 2.1])

    By examining the coefficients, we see that the line should have a
    gradient of roughly 1 and cuts the y-axis at more-or-less -1.

    We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
    and ``p = [[m], [c]]``.  Now use `lstsq` to solve for `p`:

    >>> A = np.vstack([x, np.ones(len(x))]).T
    >>> A
    array([[ 0.,  1.],
           [ 1.,  1.],
           [ 2.,  1.],
           [ 3.,  1.]])

    >>> m, c = np.linalg.lstsq(A, y)[0]
    >>> print m, c
    1.0 -0.95

    Plot the data along with the fitted line:

    >>> import matplotlib.pyplot as plt
    >>> plt.plot(x, y, 'o', label='Original data', markersize=10)
    >>> plt.plot(x, m*x + c, 'r', label='Fitted line')
    >>> plt.legend()
    >>> plt.show()

    """
    import math
    a, _ = _makearray(a)
    b, wrap = _makearray(b)
    is_1d = len(b.shape) == 1
    if is_1d:
        b = b[:, newaxis]
    _assertRank2(a, b)
    m  = a.shape[0]
    n  = a.shape[1]
    n_rhs = b.shape[1]
    ldb = max(n, m)
    if m != b.shape[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t, result_t = _commonType(a, b)
    real_t = _linalgRealType(t)
    bstar = zeros((ldb, n_rhs), t)
    bstar[:b.shape[0],:n_rhs] = b.copy()
    a, bstar = _fastCopyAndTranspose(t, a, bstar)
    s = zeros((min(m, n),), real_t)
    nlvl = max( 0, int( math.log( float(min(m, n))/2. ) ) + 1 )
    iwork = zeros((3*min(m, n)*nlvl+11*min(m, n),), fortran_int)
    if isComplexType(t):
        lapack_routine = lapack_lite.zgelsd
        lwork = 1
        rwork = zeros((lwork,), real_t)
        work = zeros((lwork,), t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond,
                                 0, work, -1, rwork, iwork, 0)
        lwork = int(abs(work[0]))
        rwork = zeros((lwork,), real_t)
        a_real = zeros((m, n), real_t)
        bstar_real = zeros((ldb, n_rhs,), real_t)
        results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m,
                                     bstar_real, ldb, s, rcond,
                                     0, rwork, -1, iwork, 0)
        lrwork = int(rwork[0])
        work = zeros((lwork,), t)
        rwork = zeros((lrwork,), real_t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond,
                                 0, work, lwork, rwork, iwork, 0)
    else:
        lapack_routine = lapack_lite.dgelsd
        lwork = 1
        work = zeros((lwork,), t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond,
                                 0, work, -1, iwork, 0)
        lwork = int(work[0])
        work = zeros((lwork,), t)
        results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond,
                                 0, work, lwork, iwork, 0)
    if results['info'] > 0:
        raise LinAlgError, 'SVD did not converge in Linear Least Squares'
    resids = array([], t)
    if is_1d:
        x = array(ravel(bstar)[:n], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_t)
    else:
        x = array(transpose(bstar)[:n,:], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = sum((transpose(bstar)[n:,:])**2, axis=0).astype(result_t)
    st = s[:min(n, m)].copy().astype(_realType(result_t))
    return wrap(x), wrap(resids), results['rank'], st
Esempio n. 58
0
 def test_2D_array(self):
     a = array([[1], [2]])
     b = array([[1], [2]])
     res = hstack([a, b])
     desired = array([[1, 1], [2, 2]])
     assert_array_equal(res, desired)
Esempio n. 59
0
 def __init__(self, data, dtype=None, copy=True):
     self.array = array(data, dtype, copy=copy)
Esempio n. 60
0
 def test_0D_array(self):
     a = array(1)
     b = array(2)
     res = [atleast_1d(a), atleast_1d(b)]
     desired = [array([1]), array([2])]
     assert_array_equal(res, desired)