Example #1
0
    def test_ufunc_out(self):
        from numpypy import array, negative, zeros, sin
        from math import sin as msin
        a = array([[1, 2], [3, 4]])
        c = zeros((2,2,2))
        b = negative(a + a, out=c[1])
        #test for view, and also test that forcing out also forces b
        assert (c[:, :, 1] == [[0, 0], [-4, -8]]).all()
        assert (b == [[-2, -4], [-6, -8]]).all()
        #Test broadcast, type promotion
        b = negative(3, out=a)
        assert (a == -3).all()
        c = zeros((2, 2), dtype=float)
        b = negative(3, out=c)
        assert b.dtype.kind == c.dtype.kind
        assert b.shape == c.shape
        a = array([1, 2])
        b = sin(a, out=c)
        assert(c == [[msin(1), msin(2)]] * 2).all()
        b = sin(a, out=c+c)
        assert (c == b).all()

        #Test shape agreement
        a = zeros((3,4))
        b = zeros((3,5))
        raises(ValueError, 'negative(a, out=b)')
        b = zeros((1,4))
        raises(ValueError, 'negative(a, out=b)')
Example #2
0
    def test_dstack(self):
        import numpypy as np
        a = np.array((1, 2, 3))
        b = np.array((2, 3, 4))
        c = np.dstack((a, b))
        assert np.array_equal(c, [[[1, 2], [2, 3], [3, 4]]])

        a = np.array([[1], [2], [3]])
        b = np.array([[2], [3], [4]])
        c = np.dstack((a, b))
        assert np.array_equal(c, [[[1, 2]], [[2, 3]], [[3, 4]]])

        #skip("https://bugs.pypy.org/issue1394")
        for shape1, shape2 in [[(4, 2, 3), (4, 2, 7)], [(7, 2, 0), (7, 2, 10)],
                               [(7, 2, 0), (7, 2, 0)]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(
                np.dstack((a, b)) == np.ones((a.shape[0], a.shape[1],
                                              a.shape[2] + b.shape[2])))

        for shape1, shape2 in [[(4, 2, 3, 5), (4, 2, 7, 5)],
                               [(7, 2, 0, 5), (7, 2, 10, 5)],
                               [(7, 2, 0, 5), (7, 2, 0, 5)]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(
                np.dstack((a, b)) == np.ones((a.shape[0], a.shape[1],
                                              a.shape[2] + b.shape[2],
                                              a.shape[3])))
Example #3
0
    def test_sort_corner_cases_string_records(self):
        skip('not implemented yet')
        from numpypy import array, dtype
        # test string sorts.
        s = 'aaaaaaaa'
        a = array([s + chr(i) for i in range(101)])
        b = a[::-1].copy()
        for kind in ['q', 'm', 'h'] :
            msg = "string 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 record array sorts.
        dt =dtype([('f', float), ('i', int)])
        a = array([(i, i) for i in range(101)], dtype = dt)
        b = a[::-1]
        for kind in ['q', 'h', 'm'] :
            msg = "object 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
 def reset_node_output_values(self, outputValues):
     
     if self.isOutputLayer:
         self.nodesOutput = np.array(outputValues)
     else:
         #Dont change the bias node value ever
         self.nodesOutput[:-1] = np.array(outputValues[:-1])
Example #5
0
 def test_choose_basic(self):
     from numpypy import array, choose
     a, b, c = array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])
     r = array([2, 1, 0]).choose([a, b, c])
     assert (r == [7, 5, 3]).all()
     r = choose(array([2, 1, 0]), [a, b, c])
     assert (r == [7, 5, 3]).all()
Example #6
0
    def test_index_int64(self):
        from numpypy import array, int64

        a = array(range(10), dtype=int64)
        b = array([0] * 10, dtype=int64)
        for idx in b:
            a[idx] += 1
Example #7
0
 def test_ufunc_cast(self):
     from _numpypy import array, negative, add, sum
     a = array(16, dtype = int)
     c = array(0, dtype = float)
     b = negative(a, out=c)
     assert b == c
     b = add(a, a, out=c)
     assert b == c
     d = array([16, 16], dtype=int)
     b = sum(d, out=c)
     assert b == c
     try:
         from _numpypy import version
         v = version.version.split('.')
     except:
         v = ['1', '6', '0'] # numpypy is api compatable to what version?
     if v[0]<'2':
         b = negative(c, out=a)
         assert b == a
         b = add(c, c, out=a)
         assert b == a
         b = sum(array([16, 16], dtype=float), out=a)
         assert b == a
     else:
         cast_error = raises(TypeError, negative, c, a)
         assert str(cast_error.value) == \
         "Cannot cast ufunc negative output from dtype('float64') to dtype('int64') with casting rule 'same_kind'"
Example #8
0
    def test_dstack(self):
        import numpypy as np
        a = np.array((1, 2, 3))
        b = np.array((2, 3, 4))
        c = np.dstack((a, b))
        assert np.array_equal(c, [[[1, 2], [2, 3], [3, 4]]])

        a = np.array([[1], [2], [3]])
        b = np.array([[2], [3], [4]])
        c = np.dstack((a, b))
        assert np.array_equal(c, [[[1, 2]], [[2, 3]], [[3, 4]]])

        #skip("https://bugs.pypy.org/issue1394")
        for shape1, shape2 in [[(4, 2, 3), (4, 2, 7)],
                               [(7, 2, 0), (7, 2, 10)],
                               [(7, 2, 0), (7, 2, 0)]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(np.dstack((a, b)) ==
                          np.ones((a.shape[0],
                                   a.shape[1],
                                   a.shape[2] + b.shape[2])))

        for shape1, shape2 in [[(4, 2, 3, 5), (4, 2, 7, 5)],
                               [(7, 2, 0, 5), (7, 2, 10, 5)],
                               [(7, 2, 0, 5), (7, 2, 0, 5)]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(np.dstack((a, b)) ==
                          np.ones((a.shape[0],
                                   a.shape[1],
                                   a.shape[2] + b.shape[2],
                                   a.shape[3])))
Example #9
0
    def test_conj(self):
        from numpypy import array

        a = array([1 + 2j, 1 - 2j])
        assert (a.conj() == [1 - 2j, 1 + 2j]).all()
        a = array([1,2,3.4J],dtype=complex)
        assert a[2].conjugate() == 0-3.4j
    def unpack(self, weight_list):
        # This method will create a list of weight matrices. Each list element
        # corresponds to the connection between two layers.
        if self.n_hidden_layers == 0:
            return [
                np.array(weight_list).reshape(self.n_inputs + 1,
                                              self.n_outputs)
            ]
        else:
            weight_layers = [
                np.array(weight_list[:(self.n_inputs + 1) *
                                     self.n_hiddens]).reshape(
                                         self.n_inputs + 1, self.n_hiddens)
            ]
            weight_layers += [
                np.array(weight_list[
                    (self.n_inputs + 1) * self.n_hiddens +
                    (i * (self.n_hiddens**2 + self.n_hiddens)):
                    (self.n_inputs + 1) * self.n_hiddens +
                    ((i + 1) * (self.n_hiddens**2 + self.n_hiddens))]).reshape(
                        self.n_hiddens + 1, self.n_hiddens)
                for i in xrange(self.n_hidden_layers - 1)
            ]
            weight_layers += [
                np.array(weight_list[(self.n_inputs + 1) * self.n_hiddens + (
                    (self.n_hidden_layers - 1) *
                    (self.n_hiddens**2 + self.n_hiddens)):]).reshape(
                        self.n_hiddens + 1, self.n_outputs)
            ]

        return weight_layers
Example #11
0
 def test_ufunc_cast(self):
     from _numpypy import array, negative, add, sum
     a = array(16, dtype=int)
     c = array(0, dtype=float)
     b = negative(a, out=c)
     assert b == c
     b = add(a, a, out=c)
     assert b == c
     d = array([16, 16], dtype=int)
     b = sum(d, out=c)
     assert b == c
     try:
         from _numpypy import version
         v = version.version.split('.')
     except:
         v = ['1', '6', '0']  # numpypy is api compatable to what version?
     if v[0] < '2':
         b = negative(c, out=a)
         assert b == a
         b = add(c, c, out=a)
         assert b == a
         b = sum(array([16, 16], dtype=float), out=a)
         assert b == a
     else:
         cast_error = raises(TypeError, negative, c, a)
         assert str(cast_error.value) == \
         "Cannot cast ufunc negative output from dtype('float64') to dtype('int64') with casting rule 'same_kind'"
Example #12
0
 def test_div_other(self):
     from numpypy import array
     a = array(range(5))
     b = array([2, 2, 2, 2, 2], float)
     c = a / b
     for i in range(5):
         assert c[i] == i / 2.0
Example #13
0
 def test_mod_other(self):
     from numpypy import array
     a = array(range(5))
     b = array([2, 2, 2, 2, 2])
     c = a % b
     for i in range(5):
         assert c[i] == i % 2
Example #14
0
 def test_pow_other(self):
     from numpypy import array
     a = array(range(5), float)
     b = array([2, 2, 2, 2, 2])
     c = a ** b
     for i in range(5):
         assert c[i] == i ** 2
Example #15
0
    def test_vstack(self):
        import numpypy as np

        a = np.array([1, 2, 3])
        b = np.array([2, 3, 4])
        c = np.vstack((a, b))
        assert np.array_equal(c, [[1, 2, 3],
                                  [2, 3, 4]])

        a = np.array([[1], [2], [3]])
        b = np.array([[2], [3], [4]])
        c = np.vstack((a, b))
        assert np.array_equal(c, [[1],
                                  [2],
                                  [3],
                                  [2],
                                  [3],
                                  [4]])

        for shape1, shape2 in [[(2, 1), (3, 1)],
                               [(2, 4), [3, 4]]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(np.vstack((a, b)) ==
                          np.ones((a.shape[0] + b.shape[0],
                                   a.shape[1])))

        #skip("https://bugs.pypy.org/issue1394")
        for shape1, shape2 in [[(3, 2, 4), (7, 2, 4)],
                               [(0, 2, 7), (10, 2, 7)],
                               [(0, 2, 7), (0, 2, 7)]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(np.vstack((a, b)) ==
                          np.ones((a.shape[0] + b.shape[0],
                                   a.shape[1],
                                   a.shape[2])))
Example #16
0
    def test_hstack(self):
        import numpypy as np
        a = np.array((1, 2, 3))
        b = np.array((2, 3, 4))
        c = np.hstack((a, b))
        assert np.array_equal(c, [1, 2, 3, 2, 3, 4])

        a = np.array([[1], [2], [3]])
        b = np.array([[2], [3], [4]])
        c = np.hstack((a, b))
        assert np.array_equal(c, [[1, 2],
                                  [2, 3],
                                  [3, 4]])

        for shape1, shape2 in [[(1, 2), (1, 3)],
                               [(4, 2), (4, 3)]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(np.hstack((a, b)) ==
                          np.ones((a.shape[0],
                                   a.shape[1] + b.shape[1])))

        #skip("https://bugs.pypy.org/issue1394")
        for shape1, shape2 in [[(2, 3, 4), (2, 7, 4)],
                               [(1, 4, 7), (1, 10, 7)],
                               [(1, 4, 7), (1, 0, 7)],
                               [(1, 0, 7), (1, 0, 7)]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(np.hstack((a, b)) ==
                          np.ones((a.shape[0],
                                   a.shape[1] + b.shape[1],
                                   a.shape[2])))
Example #17
0
    def test_vstack(self):
        import numpypy as np

        a = np.array([1, 2, 3])
        b = np.array([2, 3, 4])
        c = np.vstack((a, b))
        assert np.array_equal(c, [[1, 2, 3],
                                  [2, 3, 4]])

        a = np.array([[1], [2], [3]])
        b = np.array([[2], [3], [4]])
        c = np.vstack((a, b))
        assert np.array_equal(c, [[1],
                                  [2],
                                  [3],
                                  [2],
                                  [3],
                                  [4]])

        for shape1, shape2 in [[(2, 1), (3, 1)],
                               [(2, 4), [3, 4]]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(np.vstack((a, b)) ==
                          np.ones((a.shape[0] + b.shape[0],
                                   a.shape[1])))

        #skip("https://bugs.pypy.org/issue1394")
        for shape1, shape2 in [[(3, 2, 4), (7, 2, 4)],
                               [(0, 2, 7), (10, 2, 7)],
                               [(0, 2, 7), (0, 2, 7)]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(np.vstack((a, b)) ==
                          np.ones((a.shape[0] + b.shape[0],
                                   a.shape[1],
                                   a.shape[2])))
Example #18
0
 def test_subtract_other(self):
     from numpypy import array
     a = array(range(5))
     b = array([1, 1, 1, 1, 1])
     c = a - b
     for i in range(5):
         assert c[i] == i - 1
Example #19
0
    def test_power_float(self):
        import math
        from numpypy import power, array
        a = array([1., 2., 3.])
        b = power(a, 3)
        for i in range(len(a)):
            assert b[i] == a[i] ** 3

        a = array([1., 2., 3.])
        b = array([1., 2., 3.])
        c = power(a, b)
        for i in range(len(a)):
            assert c[i] == a[i] ** b[i]

        assert power(2, float('inf')) == float('inf')
        assert power(float('inf'), float('inf')) == float('inf')
        assert power(12345.0, 12345.0) == float('inf')
        assert power(-12345.0, 12345.0) == float('-inf')
        assert power(-12345.0, 12346.0) == float('inf')
        assert math.isnan(power(-1, 1.1))
        assert math.isnan(power(-1, -1.1))
        assert power(-2.0, -1) == -0.5
        assert power(-2.0, -2) == 0.25
        assert power(12345.0, -12345.0) == 0
        assert power(float('-inf'), 2) == float('inf')
        assert power(float('-inf'), 2.5) == float('inf')
        assert power(float('-inf'), 3) == float('-inf')
Example #20
0
    def test_abstract_types(self):
        import numpypy as numpy

        raises(TypeError, numpy.generic, 0)
        raises(TypeError, numpy.number, 0)
        raises(TypeError, numpy.integer, 0)
        exc = raises(TypeError, numpy.signedinteger, 0)
        assert 'cannot create' in str(exc.value)
        assert 'signedinteger' in str(exc.value)
        exc = raises(TypeError, numpy.unsignedinteger, 0)
        assert 'cannot create' in str(exc.value)
        assert 'unsignedinteger' in str(exc.value)
        raises(TypeError, numpy.floating, 0)
        raises(TypeError, numpy.inexact, 0)

        # numpy allows abstract types in array creation
        a_n = numpy.array([4,4], numpy.number)
        a_i = numpy.array([4,4], numpy.integer)
        a_s = numpy.array([4,4], numpy.signedinteger)
        a_u = numpy.array([4,4], numpy.unsignedinteger)

        assert a_n.dtype.num == 12
        assert a_i.dtype.num == 7
        assert a_s.dtype.num == 7
        assert a_u.dtype.num == 8

        assert a_n.dtype is numpy.dtype('float64')
        if self.ptr_size == 4:
            assert a_i.dtype is numpy.dtype('int32')
            assert a_s.dtype is numpy.dtype('int32')
            assert a_u.dtype is numpy.dtype('uint32')
        else:
            assert a_i.dtype is numpy.dtype('int64')
            assert a_s.dtype is numpy.dtype('int64')
            assert a_u.dtype is numpy.dtype('uint64')
Example #21
0
    def test_dot(self):
        from numpypy import array
        a = array(range(5))
        assert a.dot(a) == 30.0

        a = array(range(5))
        assert a.dot(range(5)) == 30
Example #22
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()
Example #23
0
 def test_add_other(self):
     from numpypy import array
     a = array(range(5))
     b = array(range(4, -1, -1))
     c = a + b
     for i in range(5):
         assert c[i] == 4
Example #24
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()
Example #25
0
 def test_fromnumeric(self):
     from numpypy import array, swapaxes
     x = array([[1,2,3]])
     assert (swapaxes(x,0,1) == array([[1], [2], [3]])).all()
     x = array([[[0,1],[2,3]],[[4,5],[6,7]]])
     assert (swapaxes(x,0,2) == array([[[0, 4], [2, 6]], 
                                       [[1, 5], [3, 7]]])).all()
Example #26
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()
Example #27
0
 def test_add_other(self):
     from numpypy import array
     a = array(range(5))
     b = array([i for i in reversed(range(5))])
     c = a + b
     for i in range(5):
         assert c[i] == 4
Example #28
0
 def test_fromnumeric(self):
     from numpypy import array, swapaxes
     x = array([[1,2,3]])
     assert (swapaxes(x,0,1) == array([[1], [2], [3]])).all()
     x = array([[[0,1],[2,3]],[[4,5],[6,7]]])
     assert (swapaxes(x,0,2) == array([[[0, 4], [2, 6]],
                                       [[1, 5], [3, 7]]])).all()
Example #29
0
    def test_hstack(self):
        import numpypy as np
        a = np.array((1, 2, 3))
        b = np.array((2, 3, 4))
        c = np.hstack((a, b))
        assert np.array_equal(c, [1, 2, 3, 2, 3, 4])

        a = np.array([[1], [2], [3]])
        b = np.array([[2], [3], [4]])
        c = np.hstack((a, b))
        assert np.array_equal(c, [[1, 2],
                                  [2, 3],
                                  [3, 4]])

        for shape1, shape2 in [[(1, 2), (1, 3)],
                               [(4, 2), (4, 3)]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(np.hstack((a, b)) ==
                          np.ones((a.shape[0],
                                   a.shape[1] + b.shape[1])))

        #skip("https://bugs.pypy.org/issue1394")
        for shape1, shape2 in [[(2, 3, 4), (2, 7, 4)],
                               [(1, 4, 7), (1, 10, 7)],
                               [(1, 4, 7), (1, 0, 7)],
                               [(1, 0, 7), (1, 0, 7)]]:
            a, b = np.ones(shape1), np.ones(shape2)
            assert np.all(np.hstack((a, b)) ==
                          np.ones((a.shape[0],
                                   a.shape[1] + b.shape[1],
                                   a.shape[2])))
Example #30
0
    def test_ufunc_out(self):
        from _numpypy import array, negative, zeros, sin
        from math import sin as msin
        a = array([[1, 2], [3, 4]])
        c = zeros((2, 2, 2))
        b = negative(a + a, out=c[1])
        #test for view, and also test that forcing out also forces b
        assert (c[:, :, 1] == [[0, 0], [-4, -8]]).all()
        assert (b == [[-2, -4], [-6, -8]]).all()
        #Test broadcast, type promotion
        b = negative(3, out=a)
        assert (a == -3).all()
        c = zeros((2, 2), dtype=float)
        b = negative(3, out=c)
        assert b.dtype.kind == c.dtype.kind
        assert b.shape == c.shape
        a = array([1, 2])
        b = sin(a, out=c)
        assert (c == [[msin(1), msin(2)]] * 2).all()
        b = sin(a, out=c + c)
        assert (c == b).all()

        #Test shape agreement
        a = zeros((3, 4))
        b = zeros((3, 5))
        raises(ValueError, 'negative(a, out=b)')
        b = zeros((1, 4))
        raises(ValueError, 'negative(a, out=b)')
Example #31
0
 def test_sum(self):
     # tests taken from numpy/core/fromnumeric.py docstring
     from numpypy import array, sum, ones
     assert sum([0.5, 1.5])== 2.0
     assert sum([[0, 1], [0, 5]]) == 6
     # assert sum([0.5, 0.7, 0.2, 1.5], dtype=int32) == 1
     assert (sum([[0, 1], [0, 5]], axis=0) == array([0, 6])).all()
     assert (sum([[0, 1], [0, 5]], axis=1) == array([1, 5])).all()
Example #32
0
    def test_add(self):
        from numpypy import array, add

        a = array([-5.0, -0.0, 1.0])
        b = array([ 3.0, -2.0,-3.0])
        c = add(a, b)
        for i in range(3):
            assert c[i] == a[i] + b[i]
Example #33
0
 def test_non_native(self):
     from numpypy import array
     a = array([1, 2, 3], dtype=self.non_native_prefix + 'g') # longdouble
     assert a[0] == 1
     assert (a + a)[1] == 4
     a = array([1, 2, 3], dtype=self.non_native_prefix + 'G') # clongdouble
     assert a[0] == 1
     assert (a + a)[1] == 4
Example #34
0
    def test_multiply(self):
        from numpypy import array, multiply

        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]
Example #35
0
    def test_minimum(self):
        from numpypy import array, minimum

        a = array([-5.0, -0.0, 1.0])
        b = array([ 3.0, -2.0,-3.0])
        c = minimum(a, b)
        for i in range(3):
            assert c[i] == min(a[i], b[i])
Example #36
0
    def test_subtract(self):
        from numpypy import array, subtract

        a = array([-5.0, -0.0, 1.0])
        b = array([ 3.0, -2.0,-3.0])
        c = subtract(a, b)
        for i in range(3):
            assert c[i] == a[i] - b[i]
Example #37
0
 def test_all(self):
     from numpypy import array
     a = array(range(5))
     assert a.all() == False
     a[0] = 3.0
     assert a.all() == True
     b = array([])
     assert b.all() == True
Example #38
0
 def test_any(self):
     from numpypy import array, zeros
     a = array(range(5))
     assert a.any() == True
     b = zeros(5)
     assert b.any() == False
     c = array([])
     assert c.any() == False
Example #39
0
    def test_sum(self):
        from numpypy import array
        a = array(range(5))
        assert a.sum() == 10.0
        assert a[:4].sum() == 6.0

        a = array([True] * 5, bool)
        assert a.sum() == 5
Example #40
0
    def test_mismatched_shape(self):
        from numpypy import array, array_equal

        a = [1, 2, 3]
        b = [[1, 2, 3], [1, 2, 3]]

        assert not array_equal(a, b)
        assert not array_equal(a, array(b))
        assert not array_equal(array(a), b)
        assert not array_equal(array(a), array(b))
Example #41
0
    def test_not_equal(self):
        from numpypy import array, array_equal

        a = [1, 2, 3]
        b = [1, 2, 4]

        assert not array_equal(a, b)
        assert not array_equal(a, array(b))
        assert not array_equal(array(a), b)
        assert not array_equal(array(a), array(b))
Example #42
0
 def test_repr_2(self):
     from numpypy import array, zeros
     int_size = array(5).dtype.itemsize
     a = array(range(5), float)
     assert repr(a) == "array([ 0.,  1.,  2.,  3.,  4.])"
     a = array([], float)
     assert repr(a) == "array([], dtype=float64)"
     a = zeros(1001)
     assert repr(a) == "array([ 0.,  0.,  0., ...,  0.,  0.,  0.])"
     a = array(range(5), int)
     if a.dtype.itemsize == int_size:
         assert repr(a) == "array([0, 1, 2, 3, 4])"
     else:
         assert repr(a) == "array([0, 1, 2, 3, 4], dtype=int64)"
     a = array(range(5), 'int32')
     if a.dtype.itemsize == int_size:
         assert repr(a) == "array([0, 1, 2, 3, 4])"
     else:
         assert repr(a) == "array([0, 1, 2, 3, 4], dtype=int32)"
     a = array([], long)
     assert repr(a) == "array([], dtype=int64)"
     a = array([True, False, True, False], "?")
     assert repr(a) == "array([ True, False,  True, False], dtype=bool)"
     a = zeros([])
     assert repr(a) == "array(0.0)"
     a = array(0.2)
     assert repr(a) == "array(0.2)"
     a = array([2])
     assert repr(a) == "array([2])"
Example #43
0
 def test_sort_nonnative(self):
     from numpypy import array
     nnp = self.non_native_prefix
     for dtype in [ nnp + 'i2']:
         a = array([6, 4, -1, 3, 8, 3, 256+20, 100, 101], dtype=dtype)
         b = array([-1, 3, 3, 4, 6, 8, 100, 101, 256+20], dtype=dtype)
         c = a.copy()
         import sys
         if '__pypy__' in sys.builtin_module_names:
             exc = raises(NotImplementedError, a.sort)
             assert exc.value[0].find('supported') >= 0
Example #44
0
 def test_applevel(self):
     from _numpypy import array, sum, max, min
     a = array([[1, 2], [3, 4]])
     out = array([[0, 0], [0, 0]])
     c = sum(a, axis=0, out=out[0])
     assert (c == [4, 6]).all()
     assert (c == out[0]).all()
     assert (c != out[1]).all()
     c = max(a, axis=1, out=out[0])
     assert (c == [2, 4]).all()
     assert (c == out[0]).all()
     assert (c != out[1]).all()
Example #45
0
 def test_argsort_axis(self):
     from numpypy import array
     a = array([])
     for axis in [None, -1, 0]:
         assert a.argsort(axis=axis).shape == (0,)
     a = array([[4, 2], [1, 3]])
     assert (a.argsort(axis=None) == [2, 1, 3, 0]).all()
     assert (a.argsort(axis=-1) == [[1, 0], [0, 1]]).all()
     assert (a.argsort(axis=0) == [[1, 0], [0, 1]]).all()
     assert (a.argsort(axis=1) == [[1, 0], [0, 1]]).all()
     a = array([[3, 2, 1], [1, 2, 3]])
     assert (a.argsort(axis=0) == [[1, 0, 0], [0, 1, 1]]).all()
     assert (a.argsort(axis=1) == [[2, 1, 0], [0, 1, 2]]).all()
Example #46
0
 def test_str_slice(self):
     from numpypy import array, zeros
     a = array(range(5), float)
     b = a[1::2]
     assert str(b) == "[ 1.  3.]"
     a = zeros(2002)
     b = a[::2]
     assert str(b) == "[ 0.  0.  0. ...,  0.  0.  0.]"
     a = array((range(5), range(5, 10)), dtype="int16")
     b = a[1, 2:]
     assert str(b) == "[7 8 9]"
     b = a[2:1, ]
     assert str(b) == "[]"
Example #47
0
 def test_repr_slice(self):
     from numpypy import array, zeros
     a = array(range(5), float)
     b = a[1::2]
     assert repr(b) == "array([ 1.,  3.])"
     a = zeros(2002)
     b = a[::2]
     assert repr(b) == "array([ 0.,  0.,  0., ...,  0.,  0.,  0.])"
     a = array((range(5), range(5, 10)), dtype="int16")
     b = a[1, 2:]
     assert repr(b) == "array([7, 8, 9], dtype=int16)"
     # an empty slice prints its shape
     b = a[2:1, ]
     assert repr(b) == "array([], shape=(0, 5), dtype=int16)"
Example #48
0
 def __init__(self, argument, id=None):
     if isinstance(argument, int):
         super(EncodedSequence, self).__init__(
             np.zeros(argument, int), id)
         self.position = 0
     else:
         if isinstance(argument, np.ndarray) \
                 and argument.dtype.name.startswith('int'):
             super(EncodedSequence, self).__init__(
                 np.array(argument), id)
         else:
             super(EncodedSequence, self).__init__(
                 np.array(list(argument), int), id)
         self.position = len(self.elements)
Example #49
0
 def test_argsort_ndim(self):
     from numpypy import array
     a = array([[4, 2], [1, 3]])
     assert (a.argsort() == [[1, 0], [0, 1]]).all()
     a = array(range(10) + range(10) + range(10))
     b = a.argsort()
     assert (b[:3] == [0, 10, 20]).all()
     #trigger timsort 'run' mode which calls arg_getitem_slice
     a = array(range(100) + range(100) + range(100))
     b = a.argsort()
     assert (b[:3] == [0, 100, 200]).all()
     a = array([[[]]]).reshape(3,4,0)
     b = a.argsort()
     assert b.size == 0
Example #50
0
    def test_vdot(self):
        import numpypy as np
        a = np.array([1 + 2j, 3 + 4j])
        b = np.array([5 + 6j, 7 + 8j])
        c = np.vdot(a, b)
        assert c == (70 - 8j)
        c = np.vdot(b, a)
        assert c == (70 + 8j)

        a = np.array([[1, 4], [5, 6]])
        b = np.array([[4, 1], [2, 2]])
        c = np.vdot(a, b)
        assert c == 30
        c = np.vdot(b, a)
        assert c == 30
Example #51
0
def solver(infile,
           testcase,
           N=None,
           P=None,
           I=None,
           T=None,
           S=None,
           C=None,
           **ignore):
    #import collections as co
    #import functools as ft
    #import itertools as it
    #import operator as op
    #import math as ma
    #import re
    import numpypy as np
    #import scipy as sp
    #import networkx as nx

    S = np.array(S)
    done = np.zeros(P, dtype=int)
    for row in range(P[0]):
        m = S[row].max()
        done[row][S[row] == m] = 1

    for col in range(P[1]):
        m = S[:, col].max()
        done[:, col][S[:, col] == m] = 1

    res = 'YES' if done.sum() == P[0] * P[1] else 'NO'
    return 'Case #%s: %s\n' % (testcase, res)
Example #52
0
 def test_outer(self):
     from numpypy import array, outer
     a = [1, 2, 3]
     b = [4, 5, 6]
     res = outer(a, b)
     expected = array([[4, 5, 6], [8, 10, 12], [12, 15, 18]])
     assert (res == expected).all()
Example #53
0
def test():
    def check(x,y):
        a = pearsonr(x,y)
        b = np.cor(x,y)
        print "pearsonr:", a
        print "corcoef:", b
        assert t_round_equal(a,b)
    x = np.array([1,2,3,5,9,12])
    y = x*2
    y[3] *= 1.5
    y[0] *= 0.6
    check(x,y) 

    import random 
    x = np.array([random.random() for _ in range(10)])
    y = np.array([random.random() for _ in range(10)])
    check(x,y)
Example #54
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))")
Example #55
0
    def test_str(self):
        from numpypy import array, zeros
        a = array(range(5), float)
        assert str(a) == "[ 0.  1.  2.  3.  4.]"
        assert str((2 * a)[:]) == "[ 0.  2.  4.  6.  8.]"
        a = zeros(1001)
        assert str(a) == "[ 0.  0.  0. ...,  0.  0.  0.]"

        a = array(range(5), dtype=long)
        assert str(a) == "[0 1 2 3 4]"
        a = array([True, False, True, False], dtype="?")
        assert str(a) == "[ True False  True False]"

        a = array(range(5), dtype="int8")
        assert str(a) == "[0 1 2 3 4]"

        a = array(range(5), dtype="int16")
        assert str(a) == "[0 1 2 3 4]"

        a = array((range(5), range(5, 10)), dtype="int16")
        assert str(a) == "[[0 1 2 3 4]\n [5 6 7 8 9]]"

        a = array(3, dtype=int)
        assert str(a) == "3"

        a = zeros((400, 400), dtype=int)
        assert str(
            a
        ) == '[[0 0 0 ..., 0 0 0]\n [0 0 0 ..., 0 0 0]\n [0 0 0 ..., 0 0 0]\n ..., \n [0 0 0 ..., 0 0 0]\n [0 0 0 ..., 0 0 0]\n [0 0 0 ..., 0 0 0]]'
        a = zeros((2, 2, 2))
        r = str(a)
        assert r == '[[[ 0.  0.]\n  [ 0.  0.]]\n\n [[ 0.  0.]\n  [ 0.  0.]]]'
Example #56
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()')
Example #57
0
def main(zods):   
    all_zods = [aqu,pis,ari,tau,gem,can,leo,vir,lib,sco,sag,cap]
    scoring_matrix = numpy.array(((0,5,10,15,10,5,0,-5,-10,-15,-10,-5),
                                  (5,0,-5,-10,-15,-10,-5,0,5,10,15,10),
                                  (10,-5,0,5,-10,15,-10,5,0,-5,10,-15),
                                  (15,-10,5,0,-5,10,-15,10,-5,0,5,-10),
                                  (10,-15,-10,-5,0,5,-10,15,10,5,0,-5),
                                  (5,-10,15,10,5,0,-5,-10,-15,10,-5,0),
                                  (0,-5,-10,-15,-10,-5,0,5,10,15,10,5),
                                  (-5,0,5,10,15,-10,5,0,-5,-10,-15,10),
                                  (-10,5,0,-5,10,-15,10,-5,0,5,-10,15),
                                  (-15,10,-5,0,5,10,15,-10,5,0,-5,-10),
                                  (-10,15,10,5,0,-5,10,-15,-10,-5,0,5),
                                  (-5,10,-15,-10,-5,0,5,10,15,-10,5,0)))

    def score(combo,combo_proc_seq,combo_len):
        running_score = [0]*combo_len
        for i in combo_proc_seq:
            running_score[i[0]] = scoring_matrix[combo[i[0]],combo[i[1]]] + scoring_matrix[combo[i[0]],combo[i[2]]]
        return running_score

    def combo_to_name(combo):
        naming = ['Aquarius','Pisces','Aries','Taurus','Gemini','Cancer','Leo','Virgo','Libra','Scorpio','Sagittarius','Capricorn']
        combo_name = []
        for i in combo:
            combo_name.append(naming[i])
        return combo_name
    
    running_best_combo = []
    running_best_combo_scores = []
    running_best_score_sum = -1000
    combo_proc_seq = []
    combo_len = len(zods)
    number_of_missing_zods = 10-combo_len
    for i in range(0,10):
        combo_proc_seq.append([i,int((i+1)%10),i-1])
    filler_combos = itertools.combinations_with_replacement(all_zods,number_of_missing_zods)
    for filler in filler_combos:
        combos = itertools.permutations(list(filler)+zods)
        for combo in combos:
            combo_score = score(combo,combo_proc_seq,10)
            sum_combo_score = sum(combo_score)
            if sum_combo_score >= running_best_score_sum:
                running_best_score_sum = sum_combo_score
                running_best_combo = combo
                running_best_combo_scores = combo_score
##            if sum(combo_score) == running_best_score_sum:
##                running_best_combo.append(combo_to_name(combo))
##                running_best_combo_scores.append(combo_score)

        print_out = []
        names = combo_to_name(running_best_combo)
        for i in range(0,len(names)):
            print_out.append('%s - %s'%(names[i],running_best_combo_scores[i]))
        print running_best_score_sum, print_out            
Example #58
0
def solver(testcase, N=None, P=None, I=None, T=None, S=None, C=None, **ignore):
    #import collections as co
    #import functools as ft
    #import itertools as it
    #import operator as op
    #import math as ma
    #import re
    import numpypy as np
    #import scipy as sp
    #import networkx as nx

    e, R, N = P
    I = np.array(I)
    E = np.array([0] * len(I))
    E[0] = e

    nexts = reversed(I.argsort())
    res = 0
    for current in nexts:
        e_next = R
        for nex in xrange(current + 1, len(E)):
            ediff = R * (nex - current - 1)
            if ediff >= e:
                break
            if E[nex] > 0:
                e_next = max(R, E[nex] - ediff)
                break

        if current + 1 < len(E) and E[current + 1] == 0:
            E[current + 1] = e_next

        if E[current] == 0:
            for prev in xrange(current - 1, -1, -1):
                ediff = R * (current - prev)
                if E[prev] > 0 or ediff >= e:
                    E[current] = min(e, E[prev] + ediff)
                    break

        res += (E[current] + R - e_next) * I[current]

    return 'Case #%s: %s\n' % (testcase, res)
Example #59
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()