예제 #1
0
    def test_sort_datetime(self):
        from numpypy import arange
        # test datetime64 sorts.
        try:
            a = arange(0, 101, dtype='datetime64[D]')
        except:
            skip('datetime type not supported yet')
        b = a[::-1]
        for kind in ['q', 'h', 'm'] :
            msg = "datetime64 sort, kind=%s" % kind
            c = a.copy();
            c.sort(kind=kind)
            assert (c == a).all(), msg
            c = b.copy();
            c.sort(kind=kind)
            assert (c == a).all(), msg

        # test timedelta64 sorts.
        a = arange(0, 101, dtype='timedelta64[D]')
        b = a[::-1]
        for kind in ['q', 'h', 'm'] :
            msg = "timedelta64 sort, kind=%s" % kind
            c = a.copy();
            c.sort(kind=kind)
            assert (c == a).all(), msg
            c = b.copy();
            c.sort(kind=kind)
            assert (c == a).all(), msg
예제 #2
0
    def test_atleast_3d(self):
        import numpypy as np

        a = np.atleast_3d(3.0)
        assert np.array_equal(a, [[[3.]]])

        x = np.arange(3.0)
        assert np.atleast_3d(x).shape == (1, 3, 1)

        x = np.arange(12.0).reshape(4, 3)
        assert np.atleast_3d(x).shape == (4, 3, 1)

        a = np.atleast_3d([1, 2])
        assert np.array_equal(a, [[[1],
                                   [2]]])
        assert a.shape == (1, 2, 1)

        a = np.atleast_3d([[1, 2]])
        assert np.array_equal(a, [[[1],
                                   [2]]])
        assert a.shape == (1, 2, 1)

        a = np.atleast_3d([[[1, 2]]])
        assert np.array_equal(a, [[[1, 2]]])
        assert a.shape == (1, 1, 2)
예제 #3
0
    def test_dot(self):
        from numpypy import array, dot, arange
        a = array(range(5))
        assert dot(a, a) == 30.0

        a = array(range(5))
        assert a.dot(range(5)) == 30
        assert dot(range(5), range(5)) == 30
        assert (dot(5, [1, 2, 3]) == [5, 10, 15]).all()

        a = arange(12).reshape(3, 4)
        b = arange(12).reshape(4, 3)
        c = a.dot(b)
        assert (c == [[ 42, 48, 54], [114, 136, 158], [186, 224, 262]]).all()

        a = arange(24).reshape(2, 3, 4)
        raises(ValueError, "a.dot(a)")
        b = a[0, :, :].T
        #Superfluous shape test makes the intention of the test clearer
        assert a.shape == (2, 3, 4)
        assert b.shape == (4, 3)
        c = dot(a, b)
        assert (c == [[[14, 38, 62], [38, 126, 214], [62, 214, 366]],
                   [[86, 302, 518], [110, 390, 670], [134, 478, 822]]]).all()
        c = dot(a, b[:, 2])
        assert (c == [[62, 214, 366], [518, 670, 822]]).all()
        a = arange(3*2*6).reshape((3,2,6))
        b = arange(3*2*6)[::-1].reshape((2,6,3))
        assert dot(a, b)[2,0,1,2] == 1140
        assert (dot([[1,2],[3,4]],[5,6]) == [17, 39]).all()
예제 #4
0
    def test_repr_multi(self):
        from numpypy import arange, zeros, array
        a = zeros((3, 4))
        assert repr(a) == '''array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])'''
        a = zeros((2, 3, 4))
        assert repr(a) == '''array([[[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]]])'''
        a = arange(1002).reshape((2, 501))
        assert repr(a) == '''array([[   0,    1,    2, ...,  498,  499,  500],
       [ 501,  502,  503, ...,  999, 1000, 1001]])'''
        assert repr(a.T) == '''array([[   0,  501],
       [   1,  502],
       [   2,  503],
       ..., 
       [ 498,  999],
       [ 499, 1000],
       [ 500, 1001]])'''
        a = arange(2).reshape((2,1))
        assert repr(a) == '''array([[0],
예제 #5
0
    def test_repr_multi(self):
        from numpypy import arange, zeros, array
        a = zeros((3, 4))
        assert repr(a) == '''array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])'''
        a = zeros((2, 3, 4))
        assert repr(a) == '''array([[[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]]])'''
        a = arange(1002).reshape((2, 501))
        assert repr(a) == '''array([[   0,    1,    2, ...,  498,  499,  500],
       [ 501,  502,  503, ...,  999, 1000, 1001]])'''
        assert repr(a.T) == '''array([[   0,  501],
       [   1,  502],
       [   2,  503],
       ..., 
       [ 498,  999],
       [ 499, 1000],
       [ 500, 1001]])'''
        a = arange(2).reshape((2, 1))
        assert repr(a) == '''array([[0],
예제 #6
0
    def test_atleast_3d(self):
        import numpypy as np

        a = np.atleast_3d(3.0)
        assert np.array_equal(a, [[[3.]]])

        x = np.arange(3.0)
        assert np.atleast_3d(x).shape == (1, 3, 1)

        x = np.arange(12.0).reshape(4, 3)
        assert np.atleast_3d(x).shape == (4, 3, 1)

        a = np.atleast_3d([1, 2])
        assert np.array_equal(a, [[[1],
                                   [2]]])
        assert a.shape == (1, 2, 1)

        a = np.atleast_3d([[1, 2]])
        assert np.array_equal(a, [[[1],
                                   [2]]])
        assert a.shape == (1, 2, 1)

        a = np.atleast_3d([[[1, 2]]])
        assert np.array_equal(a, [[[1, 2]]])
        assert a.shape == (1, 1, 2)
예제 #7
0
 def test_argmin(self):
     # tests adapted from test_argmax
     from numpypy import arange, argmin
     a = arange(6).reshape((2,3))
     assert argmin(a) == 0
     #assert (argmin(a, axis=0) == array([0, 0, 0])).all()
     #assert (argmin(a, axis=1) == array([0, 0])).all()
     b = arange(6)
     b[1] = 0
     assert argmin(b) == 0
예제 #8
0
 def test_argmax(self):
     # tests taken from numpy/core/fromnumeric.py docstring
     from numpypy import array, arange, argmax
     a = arange(6).reshape((2,3))
     assert argmax(a) == 5
     # assert (argmax(a, axis=0) == array([1, 1, 1])).all()
     # assert (argmax(a, axis=1) == array([2, 2])).all()
     b = arange(6)
     b[1] = 5
     assert argmax(b) == 1
예제 #9
0
 def test_argmin(self):
     # tests adapted from test_argmax
     from numpypy import array, arange, argmin
     a = arange(6).reshape((2,3))
     assert argmin(a) == 0
     #assert (argmin(a, axis=0) == array([0, 0, 0])).all()
     #assert (argmin(a, axis=1) == array([0, 0])).all()
     b = arange(6)
     b[1] = 0
     assert argmin(b) == 0
예제 #10
0
 def test_argmax(self):
     # tests taken from numpy/core/fromnumeric.py docstring
     from numpypy import arange, argmax
     a = arange(6).reshape((2,3))
     assert argmax(a) == 5
     # assert (argmax(a, axis=0) == array([1, 1, 1])).all()
     # assert (argmax(a, axis=1) == array([2, 2])).all()
     b = arange(6)
     b[1] = 5
     assert argmax(b) == 1
예제 #11
0
 def test_put_modes(self):
     from numpypy import array, arange
     a = arange(5)
     a.put(22, -5, mode='clip')
     assert (a == array([0, 1, 2, 3, -5])).all()
     a = arange(5)
     a.put(22, -5, mode='wrap')
     assert (a == array([0, 1, -5, 3, 4])).all()
     raises(ValueError, "arange(5).put(22, -5, mode='raise')")
     raises(ValueError, "arange(5).put(22, -5, mode='wrongmode')")
예제 #12
0
 def test_put_basic(self):
     from numpypy import arange, array
     a = arange(5)
     a.put([0, 2], [-44, -55])
     assert (a == array([-44, 1, -55, 3, 4])).all()
     a = arange(5)
     a.put([3, 4], 9)
     assert (a == array([0, 1, 2, 9, 9])).all()
     a = arange(5)
     a.put(1, [7, 8])
     assert (a == array([0, 7, 2, 3, 4])).all()
예제 #13
0
 def test_dot_out(self):
     from numpypy import arange, dot
     a = arange(12).reshape(3, 4)
     b = arange(12).reshape(4, 3)
     out = arange(9).reshape(3, 3)
     c = dot(a, b, out=out)
     assert (c == out).all()
     assert (c == [[42, 48, 54], [114, 136, 158], [186, 224, 262]]).all()
     out = arange(9, dtype=float).reshape(3, 3)
     exc = raises(ValueError, dot, a, b, out)
     assert exc.value[0] == ('output array is not acceptable (must have the '
                             'right type, nr dimensions, and be a C-Array)')
예제 #14
0
 def test_clip(self):
     import numpypy as np
     a = np.arange(10)
     b = np.clip(a, 1, 8)
     assert (b == [1, 1, 2, 3, 4, 5, 6, 7, 8, 8]).all()
     assert (a == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).all()
     b = np.clip(a, 3, 6, out=a)
     assert (b == [3, 3, 3, 3, 4, 5, 6, 6, 6, 6]).all()
     assert (a == [3, 3, 3, 3, 4, 5, 6, 6, 6, 6]).all()
     a = np.arange(10)
     b = np.clip(a, [3,4,1,1,1,4,4,4,4,4], 8)
     assert (b == [3, 4, 2, 3, 4, 5, 6, 7, 8, 8]).all()
     assert (a == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).all()
예제 #15
0
 def test_clip(self):
     import numpypy as np
     a = np.arange(10)
     b = np.clip(a, 1, 8)
     assert (b == [1, 1, 2, 3, 4, 5, 6, 7, 8, 8]).all()
     assert (a == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).all()
     b = np.clip(a, 3, 6, out=a)
     assert (b == [3, 3, 3, 3, 4, 5, 6, 6, 6, 6]).all()
     assert (a == [3, 3, 3, 3, 4, 5, 6, 6, 6, 6]).all()
     a = np.arange(10)
     b = np.clip(a, [3,4,1,1,1,4,4,4,4,4], 8)
     assert (b == [3, 4, 2, 3, 4, 5, 6, 7, 8, 8]).all()
     assert (a == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).all()
예제 #16
0
    def test_finalize(self):
        #taken from http://docs.scipy.org/doc/numpy/user/basics.subclassing.html#simple-example-adding-an-extra-attribute-to-ndarray
        import numpypy as np
        class InfoArray(np.ndarray):
            def __new__(subtype, shape, dtype=float, buffer=None, offset=0,
                          strides=None, order='C', info=None):
                obj = np.ndarray.__new__(subtype, shape, dtype, buffer,
                         offset, strides, order)
                obj.info = info
                return obj

            def __array_finalize__(self, obj):
                if obj is None:
                    print 'finalize with None'
                    return
                # printing the object itself will crash the test
                print 'finalize with something',type(obj)
                self.info = getattr(obj, 'info', None)
        obj = InfoArray(shape=(3,))
        assert isinstance(obj, InfoArray)
        assert obj.info is None
        obj = InfoArray(shape=(3,), info='information')
        assert obj.info == 'information'
        v = obj[1:]
        assert isinstance(v, InfoArray)
        assert v.base is obj
        assert v.info == 'information'
        arr = np.arange(10)
        cast_arr = arr.view(InfoArray)
        assert isinstance(cast_arr, InfoArray)
        assert cast_arr.base is arr
        assert cast_arr.info is None
예제 #17
0
    def test_comparisons(self):
        import operator
        from numpypy import (equal, not_equal, less, less_equal, greater,
                            greater_equal, arange)

        for ufunc, func in [
            (equal, operator.eq),
            (not_equal, operator.ne),
            (less, operator.lt),
            (less_equal, operator.le),
            (greater, operator.gt),
            (greater_equal, operator.ge),
        ]:
            for a, b in [
                (3, 3),
                (3, 4),
                (4, 3),
                (3.0, 3.0),
                (3.0, 3.5),
                (3.5, 3.0),
                (3.0, 3),
                (3, 3.0),
                (3.5, 3),
                (3, 3.5),
            ]:
                assert ufunc(a, b) == func(a, b)
        c = arange(10)
        val = c == 'abcdefg'
        assert val == False
예제 #18
0
    def test_amin(self):
        # tests taken from numpy/core/fromnumeric.py docstring
        from numpypy import array, arange, amin, zeros
        a = arange(4).reshape((2,2))
        assert amin(a) == 0
        # # Minima along the first axis
        # assert (amin(a, axis=0) == array([0, 1])).all()
        # # Minima along the second axis
        # assert (amin(a, axis=1) == array([0, 2])).all()
        # # NaN behaviour
        # b = arange(5, dtype=float)
        # b[2] = NaN
        # assert amin(b) == nan
        # assert nanmin(b) == 0.0

        assert amin(range(10)) == 0
        assert amin(array(range(10))) == 0
        assert list(amin(zeros((0, 2)), axis=1)) == []

        a = array([[1, 2], [3, 4]])
        out = array([[0, 0], [0, 0]])
        c = amin(a, axis=1, out=out[0])
        assert (c == [1, 3]).all()
        assert (c == out[0]).all()
        assert (c != out[1]).all()
예제 #19
0
    def test_amin(self):
        # tests taken from numpy/core/fromnumeric.py docstring
        from numpypy import array, arange, amin, zeros
        a = arange(4).reshape((2,2))
        assert amin(a) == 0
        # # Minima along the first axis
        # assert (amin(a, axis=0) == array([0, 1])).all()
        # # Minima along the second axis
        # assert (amin(a, axis=1) == array([0, 2])).all()
        # # NaN behaviour
        # b = arange(5, dtype=float)
        # b[2] = NaN
        # assert amin(b) == nan
        # assert nanmin(b) == 0.0

        assert amin(range(10)) == 0
        assert amin(array(range(10))) == 0
        assert list(amin(zeros((0, 2)), axis=1)) == []

        a = array([[1, 2], [3, 4]])
        out = array([[0, 0], [0, 0]])
        c = amin(a, axis=1, out=out[0])
        assert (c == [1, 3]).all()
        assert (c == out[0]).all()
        assert (c != out[1]).all()
예제 #20
0
 def test_put_modes(self):
     from numpypy import array, arange
     a = arange(5)
     a.put(22, -5, mode='clip')
     assert (a == array([0, 1, 2, 3, -5])).all()
     a = arange(5)
     a.put(22, -5, mode='wrap')
     assert (a == array([0, 1, -5, 3, 4])).all()
     raises(IndexError, "arange(5).put(22, -5, mode='raise')")
     raises(IndexError, "arange(5).put(22, -5, mode=2)")  # raise
     a.put(22, -10, mode='wrongmode_starts_with_w_so_wrap')
     assert (a == array([0, 1, -10, 3, 4])).all()
     a.put(22, -15, mode='cccccccc')
     assert (a == array([0, 1, -10, 3, -15])).all()
     a.put(23, -1, mode=1)  # wrap
     assert (a == array([0, 1, -10, -1, -15])).all()
     raises(TypeError, "arange(5).put(22, -5, mode='zzzz')")  # unrecognized mode
예제 #21
0
def only_first_factor(n):
  primes = []
  candidates = np.arange(2, int(np.sqrt(n)))
  for candidate in candidates:
    if n % candidate == 0:
      primes.append(candidate)
      break      
  return primes
예제 #22
0
 def test_transpose(self):
     from numpypy import arange, array, transpose, ones
     x = arange(4).reshape((2,2))
     assert (transpose(x) == array([[0, 2],[1, 3]])).all()
     # Once axes argument is implemented, add more tests
     import sys
     if '__pypy__' in sys.builtin_module_names:
         raises(NotImplementedError, "transpose(x, axes=(1, 0, 2))")
예제 #23
0
def only_first_factor(n):
    primes = []
    candidates = np.arange(2, int(np.sqrt(n)))
    for candidate in candidates:
        if n % candidate == 0:
            primes.append(candidate)
            break
    return primes
예제 #24
0
 def test_bitwise(self):
     from numpypy import bitwise_and, bitwise_or, bitwise_xor, arange, array
     a = arange(6).reshape(2, 3)
     assert (a & 1 == [[0, 1, 0], [1, 0, 1]]).all()
     assert (a & 1 == bitwise_and(a, 1)).all()
     assert (a | 1 == [[1, 1, 3], [3, 5, 5]]).all()
     assert (a | 1 == bitwise_or(a, 1)).all()
     assert (a ^ 3 == bitwise_xor(a, 3)).all()
     raises(TypeError, 'array([1.0]) & 1')
예제 #25
0
파일: test_numeric.py 프로젝트: sota/pypy
 def test_argwhere(self):
     import numpypy as np
     x = np.arange(6).reshape(2,3)
     a = np.argwhere(x>1)
     assert np.array_equal(a,
         [[0, 2],
         [1, 0],
         [1, 1],
         [1, 2]]
     )
예제 #26
0
    def test_multiply(self):
        from numpypy import array, multiply, arange

        a = array([-5.0, -0.0, 1.0])
        b = array([ 3.0, -2.0,-3.0])
        c = multiply(a, b)
        for i in range(3):
            assert c[i] == a[i] * b[i]

        a = arange(15).reshape(5, 3)
        assert(multiply.reduce(a) == array([0, 3640, 12320])).all()
예제 #27
0
 def test_accumulate(self):
     from numpypy import add, subtract, multiply, divide, arange, dtype
     assert (add.accumulate([2, 3, 5]) == [2, 5, 10]).all()
     assert (multiply.accumulate([2, 3, 5]) == [2, 6, 30]).all()
     a = arange(4).reshape(2,2)
     b = add.accumulate(a, axis=0)
     assert (b == [[0, 1], [2, 4]]).all()
     b = add.accumulate(a, 1)
     assert (b == [[0, 1], [2, 5]]).all()
     b = add.accumulate(a) #default axis is 0
     assert (b == [[0, 1], [2, 4]]).all()
     # dtype
     a = arange(0, 3, 0.5).reshape(2, 3)
     b = add.accumulate(a, dtype=int, axis=1)
     print b
     assert (b == [[0, 0, 1], [1, 3, 5]]).all()
     assert b.dtype == int
     assert add.accumulate([True]*200)[-1] == 200
     assert add.accumulate([True]*200).dtype == dtype('int')
     assert subtract.accumulate([True]*200).dtype == dtype('bool')
     assert divide.accumulate([True]*200).dtype == dtype('int8')
예제 #28
0
 def test_reduce_out(self):
     from numpypy import arange, zeros, array
     a = arange(15).reshape(5, 3)
     b = arange(12).reshape(4,3)
     c = a.sum(0, out=b[1])
     assert (c == [30, 35, 40]).all()
     assert (c == b[1]).all()
     raises(ValueError, 'a.prod(0, out=arange(10))')
     a=arange(12).reshape(3,2,2)
     raises(ValueError, 'a.sum(0, out=arange(12).reshape(3,2,2))')
     raises(ValueError, 'a.sum(0, out=arange(3))')
     c = array([-1, 0, 1]).sum(out=zeros([], dtype=bool))
     #You could argue that this should product False, but
     # that would require an itermediate result. Cpython numpy
     # gives True.
     assert c == True
     a = array([[-1, 0, 1], [1, 0, -1]])
     c = a.sum(0, out=zeros((3,), dtype=bool))
     assert (c == [True, False, True]).all()
     c = a.sum(1, out=zeros((2,), dtype=bool))
     assert (c == [True, True]).all()
예제 #29
0
 def test_reshape(self):
     from numpypy import arange, array, dtype, reshape
     a = arange(12)
     b = reshape(a, (3, 4))
     assert b.shape == (3, 4)
     a = range(12)
     b = reshape(a, (3, 4))
     assert b.shape == (3, 4)
     a = array(range(105)).reshape(3, 5, 7)
     assert reshape(a, (1, -1)).shape == (1, 105)
     assert reshape(a, (1, 1, -1)).shape == (1, 1, 105)
     assert reshape(a, (-1, 1, 1)).shape == (105, 1, 1)
예제 #30
0
 def test_reshape(self):
     from numpypy import arange, array, dtype, reshape
     a = arange(12)
     b = reshape(a, (3, 4))
     assert b.shape == (3, 4)
     a = range(12)
     b = reshape(a, (3, 4))
     assert b.shape == (3, 4)
     a = array(range(105)).reshape(3, 5, 7)
     assert reshape(a, (1, -1)).shape == (1, 105)
     assert reshape(a, (1, 1, -1)).shape == (1, 1, 105)
     assert reshape(a, (-1, 1, 1)).shape == (105, 1, 1)
예제 #31
0
 def test_reduce_out(self):
     from numpypy import arange, zeros, array
     a = arange(15).reshape(5, 3)
     b = arange(12).reshape(4, 3)
     c = a.sum(0, out=b[1])
     assert (c == [30, 35, 40]).all()
     assert (c == b[1]).all()
     raises(ValueError, 'a.prod(0, out=arange(10))')
     a = arange(12).reshape(3, 2, 2)
     raises(ValueError, 'a.sum(0, out=arange(12).reshape(3,2,2))')
     raises(ValueError, 'a.sum(0, out=arange(3))')
     c = array([-1, 0, 1]).sum(out=zeros([], dtype=bool))
     #You could argue that this should product False, but
     # that would require an itermediate result. Cpython numpy
     # gives True.
     assert c == True
     a = array([[-1, 0, 1], [1, 0, -1]])
     c = a.sum(0, out=zeros((3, ), dtype=bool))
     assert (c == [True, False, True]).all()
     c = a.sum(1, out=zeros((2, ), dtype=bool))
     assert (c == [True, True]).all()
예제 #32
0
    def test_sort_dtypes(self):
        from numpypy import array, arange
        for dtype in ['int', 'float', 'int16', 'float32', 'uint64',
                      'i2', complex]:
            a = array([6, 4, -1, 3, 8, 3, 256+20, 100, 101], dtype=dtype)
            exp = sorted(list(a))
            res = a.copy()
            res.sort()
            assert (res == exp).all(), '%r\n%r\n%r' % (a,res,exp)

            a = arange(100, dtype=dtype)
            c = a.copy()
            a.sort()
            assert (a == c).all()
예제 #33
0
    def test_atleast_2d(self):
        import numpypy as np
        a = np.atleast_2d(3.0)
        assert np.array_equal(a, [[3.]])

        x = np.arange(3.0)
        a = np.atleast_2d(x)
        assert np.array_equal(a, [[0., 1., 2.]])

        a = np.atleast_2d(1, [1, 2], [[1, 2]])
        assert len(a) == 3
        assert np.array_equal(a[0], [[1]])
        assert np.array_equal(a[1], [[1, 2]])
        assert np.array_equal(a[2], [[1, 2]])
예제 #34
0
    def test_atleast_2d(self):
        import numpypy as np
        a = np.atleast_2d(3.0)
        assert np.array_equal(a, [[3.]])

        x = np.arange(3.0)
        a = np.atleast_2d(x)
        assert np.array_equal(a, [[0., 1., 2.]])

        a = np.atleast_2d(1, [1, 2], [[1, 2]])
        assert len(a) == 3
        assert np.array_equal(a[0], [[1]])
        assert np.array_equal(a[1], [[1, 2]])
        assert np.array_equal(a[2], [[1, 2]])
예제 #35
0
    def test_atleast_1d(self):
        from numpypy import array, array_equal
        import numpypy as np
        a = np.atleast_1d(1.0)
        assert np.array_equal(a, [1.])

        x = np.arange(9.0).reshape(3, 3)
        a = np.atleast_1d(x)
        assert np.array_equal(a, [[0.,  1.,  2.],
                                  [3.,  4.,  5.],
                                  [6.,  7.,  8.]])
        assert np.atleast_1d(x) is x

        a = np.atleast_1d(1, [3, 4])
        assert len(a) == 2
        assert array_equal(a[0], [1])
        assert array_equal(a[1], [3, 4])
예제 #36
0
    def test_atleast_1d(self):
        from numpypy import array, array_equal
        import numpypy as np
        a = np.atleast_1d(1.0)
        assert np.array_equal(a, [1.])

        x = np.arange(9.0).reshape(3, 3)
        a = np.atleast_1d(x)
        assert np.array_equal(a, [[0.,  1.,  2.],
                                  [3.,  4.,  5.],
                                  [6.,  7.,  8.]])
        assert np.atleast_1d(x) is x

        a = np.atleast_1d(1, [3, 4])
        assert len(a) == 2
        assert array_equal(a[0], [1])
        assert array_equal(a[1], [3, 4])
예제 #37
0
    def test_argsort_dtypes(self):
        from numpypy import array, arange
        assert array(2.0).argsort() == 0
        nnp = self.non_native_prefix
        for dtype in ['int', 'float', 'int16', 'float32', 'uint64',
                      nnp + 'i2', complex]:
            a = array([6, 4, -1, 3, 8, 3, 256+20, 100, 101], dtype=dtype)
            exp = list(a)
            exp = sorted(range(len(exp)), key=exp.__getitem__)
            c = a.copy()
            res = a.argsort()
            assert (res == exp).all(), '%r\n%r\n%r' % (a,res,exp)
            assert (a == c).all() # not modified

            a = arange(100, dtype=dtype)
            assert (a.argsort() == a).all()
        import sys
        if '__pypy__' in sys.builtin_module_names:
            raises(NotImplementedError, 'arange(10,dtype="float16").argsort()')
예제 #38
0
 def test_arange(self):
     from numpypy import arange, array, dtype
     a = arange(3)
     assert (a == [0, 1, 2]).all()
     assert a.dtype is dtype(int)
     a = arange(3.0)
     assert (a == [0., 1., 2.]).all()
     assert a.dtype is dtype(float)
     a = arange(3, 7)
     assert (a == [3, 4, 5, 6]).all()
     assert a.dtype is dtype(int)
     a = arange(3, 7, 2)
     assert (a == [3, 5]).all()
     a = arange(3, dtype=float)
     assert (a == [0., 1., 2.]).all()
     assert a.dtype is dtype(float)
     a = arange(0, 0.8, 0.1)
     assert len(a) == 8
     assert arange(False, True, True).dtype is dtype(int)
예제 #39
0
    def test_amax(self):
        # tests taken from numpy/core/fromnumeric.py docstring
        from numpypy import array, arange, amax, zeros
        a = arange(4).reshape((2,2))
        assert amax(a) == 3
        # assert (amax(a, axis=0) == array([2, 3])).all()
        # assert (amax(a, axis=1) == array([1, 3])).all()
        # # NaN behaviour
        # b = arange(5, dtype=float)
        # b[2] = NaN
        # assert amax(b) == nan
        # assert nanmax(b) == 4.0

        assert amax(range(10)) == 9
        assert amax(array(range(10))) == 9
        assert list(amax(zeros((0, 2)), axis=1)) == []

        a = array([[1, 2], [3, 4]])
        out = array([[0, 0], [0, 0]])
        c = amax(a, axis=1, out=out[0])
        assert (c == [2, 4]).all()
        assert (c == out[0]).all()
        assert (c != out[1]).all()
예제 #40
0
    def test_amax(self):
        # tests taken from numpy/core/fromnumeric.py docstring
        from numpypy import array, arange, amax, zeros
        a = arange(4).reshape((2,2))
        assert amax(a) == 3
        # assert (amax(a, axis=0) == array([2, 3])).all()
        # assert (amax(a, axis=1) == array([1, 3])).all()
        # # NaN behaviour
        # b = arange(5, dtype=float)
        # b[2] = NaN
        # assert amax(b) == nan
        # assert nanmax(b) == 4.0

        assert amax(range(10)) == 9
        assert amax(array(range(10))) == 9
        assert list(amax(zeros((0, 2)), axis=1)) == []

        a = array([[1, 2], [3, 4]])
        out = array([[0, 0], [0, 0]])
        c = amax(a, axis=1, out=out[0])
        assert (c == [2, 4]).all()
        assert (c == out[0]).all()
        assert (c != out[1]).all()
예제 #41
0
 def test_reduce_intermediary(self):
     from numpypy import arange, array
     a = arange(15).reshape(5, 3)
     b = array(range(3), dtype=bool)
     c = a.prod(0, out=b)
     assert(b == [False,  True,  True]).all()
예제 #42
0
mTransition = np.array([[0.9727, 0.0273, 0.0000, 0.0000, 0.0000],
                        [0.0041, 0.9806, 0.0153, 0.0000, 0.0000],
                        [0.0000, 0.0082, 0.9837, 0.0082, 0.0000],
                        [0.0000, 0.0000, 0.0153, 0.9806, 0.0041],
                        [0.0000, 0.0000, 0.0000, 0.0273, 0.9727]], float)

## 2. Steady State

capitalSteadyState = (aalpha * bbeta)**(1 / (1 - aalpha))
outputSteadyState = capitalSteadyState**aalpha
consumptionSteadyState = outputSteadyState - capitalSteadyState

print "Output = ", outputSteadyState, " Capital = ", capitalSteadyState, " Consumption = ", consumptionSteadyState

# We generate the grid of capital
vGridCapital = np.arange(0.5 * capitalSteadyState, 1.5 * capitalSteadyState,
                         0.00001)

nGridCapital = len(vGridCapital)
nGridProductivity = len(vProductivity)

## 3. Required matrices and vectors

mOutput = np.zeros((nGridCapital, nGridProductivity), dtype=float)
mValueFunction = np.zeros((nGridCapital, nGridProductivity), dtype=float)
mValueFunctionNew = np.zeros((nGridCapital, nGridProductivity), dtype=float)
mPolicyFunction = np.zeros((nGridCapital, nGridProductivity), dtype=float)
expectedValueFunction = np.zeros((nGridCapital, nGridProductivity),
                                 dtype=float)

# 4. We pre-build output for each point in the grid
예제 #43
0
import random
import math
import numpypy as np

a = np.arange(2, int(np.sqrt(10000000)))
def MillerRabin(n):
    if np.any(n % a == 0):
        return False
    return True

def keygen(bits):
    p = q = 3
    while p == q:
        p = random.randint(2**(bits/2-2),2**(bits/2))
        q = random.randint(2**(bits/2-2),2**(bits/2))
        p += not(p&1)                             # changes the values from 
        q += not(q&1)                             # even to odd

        while MillerRabin(p) == False:            # checks for primality
            p -= 2
        while MillerRabin(q) == False:
            q -= 2
    n = p * q   
    tot = (p-1) * (q-1)
    e = tot
    return e

print keygen(200)
try:
    import numpypy as np
except ImportError:
    import numpy as np

from mediansmooth import *

N = 1000000
#x = np.linspace(0, 2*np.pi, N)
x = np.arange(N) * (2*np.pi / (N - 1))
y = np.sin(x)

#y += 0.5*(2*np.random.random(x.size)-1)

ind2 = mediansmooth_old(y, 100)

print ind2[:20]

try:
    import matplotlib.pyplot as plt
except ImportError:
    pass
else:
    plt.plot(x, y, x, y[ind2])
    plt.show()

예제 #45
0
try:
    import numpypy as np
except ImportError:
    import numpy as np

import specfun

N = 1000
x = np.arange(N) * (3. / (N - 1))
y = x.copy()

specfun.specfun('besei0', y)

print y[:20]

try:
    from matplotlib.pylab import plot, show
except ImportError:
    pass
else:
    plot(x, y)
    show()
예제 #46
0
 def test_mean(self):
     from numpypy import array, mean, arange
     assert mean(array(range(5))) == 2.0
     assert mean(range(5)) == 2.0
     assert (mean(arange(10).reshape(5, 2), axis=0) == [4, 5]).all()
     assert (mean(arange(10).reshape(5, 2), axis=1) == [0.5, 2.5, 4.5, 6.5, 8.5]).all()
예제 #47
0
 def test_reduce_intermediary(self):
     from numpypy import arange, array
     a = arange(15).reshape(5, 3)
     b = array(range(3), dtype=bool)
     c = a.prod(0, out=b)
     assert (b == [False, True, True]).all()
예제 #48
0
 def test_amax(self):
     # tests taken from numpy/core/fromnumeric.py docstring
     from numpypy import array, arange, amax
     a = arange(4).reshape((2,2))
     assert amax(a) == 3
예제 #49
0
 def test_flatnonzero(self):
     import numpypy as np
     x = np.arange(-2, 3)
     a = np.flatnonzero(x)
     assert np.array_equal(a, [0, 1, 3, 4])
예제 #50
0
import math
import numpypy as np


def isPrime(n):
    for x in np.arange(2, int(np.sqrt(n))):
        if n % x == 0:
            return False
    return True


def only_first_factor(n):
    primes = []
    candidates = np.arange(2, int(np.sqrt(n)))
    for candidate in candidates:
        if n % candidate == 0:
            primes.append(candidate)
            break
    return primes


factors = []
for n in np.arange(0, 10000):
    value = n * n - n + 37
    if not isPrime(value):
        factors.append(only_first_factor(value)[0])

print factors
예제 #51
0
            do_var = ptr(do_var)
        getattr(ff, name_fit)(P.size, ptr(P), x.size, ptr(x), ptr(y),
                              ptr(ydata), ptr(a), do_var)
        return P

    return fun, fun_diff, fun_rms, fun_fit


e2, e2_diff, e2_rms, e2_fit = _fun_factory('_e2')
IV3, IV3_diff, IV3_rms, IV3_fit = _fun_factory('_IV3')
IVdbl, IVdbl_diff, IVdbl_rms, IVdbl_fit = _fun_factory('_IVdbl')

IV4, IV4_diff, IV4_rms, IV4_fit = _fun_a_factory('_IV4')
IV5, IV5_diff, IV5_rms, IV5_fit = _fun_a_factory('_IV5')
IV6, IV6_diff, IV6_rms, IV6_fit = _fun_a_factory('_IV6')
IVdbl2, IVdbl2_diff, IVdbl2_rms, IVdbl2_fit = _fun_a_factory('_IVdbl2')

if __name__ == "__main__":
    try:
        import numpypy as np
    except ImportError:
        import numpy as np

    P = np.array([1., 1.])
    x = np.arange(4.)
    y = np.empty(x.shape, x.dtype)

    print e2(P, x, y)

    print P[0] * np.exp(-P[1] * x)
예제 #52
0
def isPrime(n):
    for x in np.arange(2, int(np.sqrt(n))):
        if n % x == 0:
            return False
    return True
예제 #53
0
 def test_reduceND(self):
     from numpypy import add, arange
     a = arange(12).reshape(3, 4)
     assert (add.reduce(a, 0) == [12, 15, 18, 21]).all()
     assert (add.reduce(a, 1) == [6.0, 22.0, 38.0]).all()
예제 #54
0
    def test_sort_corner_cases(self):
        # test ordering for floats and complex containing nans. It is only
        # necessary to check the lessthan comparison, so sorts that
        # only follow the insertion sort path are sufficient. We only
        # test doubles and complex doubles as the logic is the same.

        # check doubles
        from numpypy import array, zeros, arange
        from math import isnan
        nan = float('nan')
        a = array([nan, 1, 0])
        b = a.copy()
        b.sort()
        assert [isnan(bb) for bb in b] == [isnan(aa) for aa in a[::-1]]
        assert (b[:2] == a[::-1][:2]).all()

        b = a.argsort()
        assert (b == [2, 1, 0]).all()

        # check complex
        a = zeros(9, dtype='complex128')
        a.real += [nan, nan, nan, 1, 0, 1, 1, 0, 0]
        a.imag += [nan, 1, 0, nan, nan, 1, 0, 1, 0]
        b = a.copy()
        b.sort()
        assert [isnan(bb) for bb in b] == [isnan(aa) for aa in a[::-1]]
        assert (b[:4] == a[::-1][:4]).all()

        b = a.argsort()
        assert (b == [8, 7, 6, 5, 4, 3, 2, 1, 0]).all()

        # all c scalar sorts use the same code with different types
        # so it suffices to run a quick check with one type. The number
        # of sorted items must be greater than ~50 to check the actual
        # algorithm because quick and merge sort fall over to insertion
        # sort for small arrays.
        a = arange(101)
        b = a[::-1].copy()
        for kind in ['q', 'm', 'h'] :
            msg = "scalar sort, kind=%s" % kind
            c = a.copy();
            c.sort(kind=kind)
            assert (c == a).all(), msg
            c = b.copy();
            c.sort(kind=kind)
            assert (c == a).all(), msg

        # test complex sorts. These use the same code as the scalars
        # but the compare fuction differs.
        ai = a*1j + 1
        bi = b*1j + 1
        for kind in ['q', 'm', 'h'] :
            msg = "complex sort, real part == 1, kind=%s" % kind
            c = ai.copy();
            c.sort(kind=kind)
            assert (c == ai).all(), msg
            c = bi.copy();
            c.sort(kind=kind)
            assert (c == ai).all(), msg
        ai = a + 1j
        bi = b + 1j
        for kind in ['q', 'm', 'h'] :
            msg = "complex sort, imag part == 1, kind=%s" % kind
            c = ai.copy();
            c.sort(kind=kind)
            assert (c == ai).all(), msg
            c = bi.copy();
            c.sort(kind=kind)
            assert (c == ai).all(), msg

        # check axis handling. This should be the same for all type
        # specific sorts, so we only check it for one type and one kind
        a = array([[3, 2], [1, 0]])
        b = array([[1, 0], [3, 2]])
        c = array([[2, 3], [0, 1]])
        d = a.copy()
        d.sort(axis=0)
        assert (d == b).all(), "test sort with axis=0"
        d = a.copy()
        d.sort(axis=1)
        assert (d == c).all(), "test sort with axis=1"
        d = a.copy()
        d.sort()
        assert (d == c).all(), "test sort with default axis"
예제 #55
0
 def test_argwhere(self):
     import numpypy as np
     x = np.arange(6).reshape(2, 3)
     a = np.argwhere(x > 1)
     assert np.array_equal(a, [[0, 2], [1, 0], [1, 1], [1, 2]])