Пример #1
0
    def test_str(self):
        from numpypy import array, zeros
        a = array(range(5), float)
        assert str(a) == "[0.0 1.0 2.0 3.0 4.0]"
        assert str((2 * a)[:]) == "[0.0 2.0 4.0 6.0 8.0]"
        a = zeros(1001)
        assert str(a) == "[0.0 0.0 0.0 ..., 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 0.0]\n  [0.0 0.0]]\n\n [[0.0 0.0]\n  [0.0 0.0]]]'
Пример #2
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)')
Пример #3
0
def matrix_multiply(a, b):
    """Takes two matrices and does a complicated matrix multiply.  Yes that one.
    NOTE: THIS APPEARS TO BE VERY BROKEN
    """
    if len(a.shape) == 1:
        nrows, = a.shape
        a = np.zeros((nrows, 1))

    if len(b.shape) == 1:
        bc, = b.shape
        if bc == a.shape[1]:
            b = np.zeros((bc, 1))
        else:
            b = np.zeros((1, bc))
       
    nrows,ac = a.shape
    bc,ncols = b.shape

    assert ac == bc
    if ispypy():
        n = np.zeros((nrows, ncols))
        for i in xrange(nrows):
            for j in xrange(ncols):
                n[i,j] = np.sum(a[i] * b[:,j])
        return n
    else:
        np.dot(a, b)
Пример #4
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])"
Пример #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_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.]]]'
Пример #7
0
    def __init__(self, *args, **kargs):
        # save the default parameters
        for param, value in self.param_list.items():
            setattr(self, param, value)

        # override if necessary
        for param, value in kargs.items():
            if param not in self.param_list:
                raise Exception("`%s' not recognized" % param)
            else:
                setattr(self, param, value)

        # set the initial values
        self.t = 0
        self.niter = 0
        self.dz = 1/(self.Nz-1)

        # some usefull quantities
        self.oodz2 = 1/self.dz**2
        self.pi = np.pi

        # create the inner fields
        self.T = Temp(self)
        self.omega = Vort(self)
        self.psi = Stream(self)

        # previous fields for critical Ra number
        self.T_old = np.zeros((self.NFourier,))
        self.omega_old = np.zeros((self.NFourier,))
        self.psi_old = np.zeros((self.NFourier,))
Пример #8
0
 def test_broadcast_wrong_shapes(self):
     from numpypy import zeros
     a = zeros((4, 3, 2))
     b = zeros((4, 2))
     exc = raises(ValueError, lambda: a + b)
     assert str(exc.value) == "operands could not be broadcast" \
         " together with shapes (4,3,2) (4,2)"
Пример #9
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],
Пример #10
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)')
Пример #11
0
 def __init__(self, neuralLayerNum, numNodes, nextNeuralLayerNumNodes):
     
     if nextNeuralLayerNumNodes != None:
         self.numNodes = numNodes+1
         self.isOutputLayer = False
         self.transMat = np.ones([self.numNodes, nextNeuralLayerNumNodes+1], dtype=float)
         
         self.rpropDelta = DEL_INIT * np.ones([self.numNodes, nextNeuralLayerNumNodes+1], dtype=float)
         self.rpropDelEDelW = np.ones([self.numNodes, nextNeuralLayerNumNodes+1], dtype=float)
         self.rpropEdgesDelta = np.zeros([self.numNodes, nextNeuralLayerNumNodes+1], dtype=float)
     else:
         #Output layer
         self.numNodes = numNodes
         self.isOutputLayer = True
         self.transMat = None
         
         self.rpropDelta = None
         self.rpropDelEDelW = None
         self.rpropEdgesDelta = None
     
     self.neuralLayerNum = neuralLayerNum
     self.nodesInput = np.zeros([self.numNodes], dtype=float)
     self.nodesOutput = np.zeros([self.numNodes], dtype=float)
     self.nodesDelta = np.zeros([self.numNodes], dtype=float)
     
     #set the bias node output to 1. and it never changes
     if not self.isOutputLayer:
         self.nodesOutput[-1] = 1.
Пример #12
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])"
Пример #13
0
def simulate_jumps(N, n, r):
    x = np.zeros(N)
    y = np.zeros(N)
    for i in range(N):
        xy = generate_n_jump(n, r)
        x[i] = xy[0]
        y[i] = xy[1]
    return x, y
Пример #14
0
 def test_repr_multi(self):
     from numpypy import array, zeros
     a = zeros((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 = zeros((2, 3, 4))
     assert repr(a) == '''array([[[0.0, 0.0, 0.0, 0.0],
Пример #15
0
 def test_shape(self):
     import numpypy
     assert numpypy.zeros(1).shape == (1,)
     assert numpypy.zeros((2, 2)).shape == (2, 2)
     assert numpypy.zeros((3, 1, 2)).shape == (3, 1, 2)
     assert numpypy.array([[1], [2], [3]]).shape == (3, 1)
     assert len(numpypy.zeros((3, 1, 2))) == 3
     raises(TypeError, len, numpypy.zeros(()))
     raises(ValueError, numpypy.array, [[1, 2], 3])
Пример #16
0
 def test_broadcast_shape_agreement(self):
     from numpypy import zeros, array
     a = zeros((3, 1, 3))
     b = array(((10, 11, 12), (20, 21, 22), (30, 31, 32)))
     c = ((a + b) == [b, b, b])
     assert c.all()
     a = array((((10, 11, 12), ), ((20, 21, 22), ), ((30, 31, 32), )))
     assert(a.shape == (3, 1, 3))
     d = zeros((3, 3))
     c = ((a + d) == [b, b, b])
     c = ((a + d) == array([[[10., 11., 12.]] * 3,
                            [[20., 21., 22.]] * 3, [[30., 31., 32.]] * 3]))
     assert c.all()
 def __init__(self, neuralLayerNum, numNodes, nextNeuralLayerNumNodes):
     
     self.numNodes = numNodes
     self.neuralLayerNum = neuralLayerNum
     self.nodesInput = np.zeros([self.numNodes], dtype=float)
     self.nodesOutput = np.zeros([self.numNodes], dtype=float)
     self.nodesDelta = np.zeros([self.numNodes], dtype=float)
     
     if nextNeuralLayerNumNodes != None:
         self.isOutputLayer = False
         self.transMat = np.ones([self.numNodes, nextNeuralLayerNumNodes], dtype=float)
     else:
         self.isOutputLayer = True
         self.transMat = None
Пример #18
0
def get_matrix(n):
    import random
    x = numpy.zeros((n,n), dtype=numpy.float64)
    for i in range(n):
        for j in range(n):
            x[i][j] = random.random()
    return x
Пример #19
0
def pyloop(a, b, c):
    N = len(a)
    assert N == len(b) == len(c)
    res = numpy.zeros(N)
    for i in range(N):
        res[i] = a[i] + b[i] * c[i]
    return res
Пример #20
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()
Пример #21
0
def fall(curx,cury,num,diamonds,totalnum,offset):
    #print diamonds
    if num <= 0:
        #import pdb; pdb.set_trace()
        zeros = numpy.zeros([totalnum,totalnum])
        #print zeros
        for d in diamonds:
            zeros[d[0]+offset,d[1]] = 1.0
        return zeros


    while (cury > 0):
        cury-=1

        # move
        left = [curx-1,cury-1] in diamonds
        right = [curx+1,cury-1] in diamonds

        if left and right:
            #end
            diamonds.append([curx,cury])
            return fall(0,100,num-1,list(diamonds),totalnum,offset)
        elif left:
            curx += 1
        elif right:
            curx -= 1
        elif [curx,cury-2] in diamonds:
            # prob
            leftprob = fall(curx-1,cury,num,list(diamonds),totalnum,offset)
            rightprob = fall(curx+1,cury,num,list(diamonds),totalnum,offset)
            return .5*leftprob+.5*rightprob
   

    diamonds.append([curx,cury])
    return fall(0,10000,num-1,list(diamonds),totalnum,offset)
Пример #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()
Пример #23
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)
Пример #24
0
def lda_recalculate_beta(text, beta, phi):
    """
    update topics: βk,wnew ∝ ΣdΣn 1(wd,n = w) φkd,n

    Accepts beta matrix (KxW) and 
        phi, a D-length list of (N x K) matrices.
    """
    (K,W) = beta.shape
    D = len(phi)
    beta[:,:] = np.zeros(beta.shape)    

    if isinstance(text[0], np.ndarray):
        for d in xrange(D):
            ensure(phi[d].shape[1] == K)
            for n,word in enumerate(text[d]):
                beta[:,word] += phi[d][n,:]
            #words, indexes = text[d], np.array(range(len(text[d])))
            #beta[:,words] += phi[d][indexes,:].T
    else:
        for d in xrange(D):
            ensure(phi[d].shape[1] == K)
            for n,word,count in iterwords(text[d]):
                beta[:,word] += phi[d][n,:]
    graphlib.row_normalize(beta)
    return beta
Пример #25
0
 def test_slices(self):
     import numpypy
     a = numpypy.zeros((4, 3, 2))
     raises(IndexError, a.__getitem__, (4,))
     raises(IndexError, a.__getitem__, (3, 3))
     raises(IndexError, a.__getitem__, (slice(None), 3))
     a[0, 1, 1] = 13
     a[1, 2, 1] = 15
     b = a[0]
     assert len(b) == 3
     assert b.shape == (3, 2)
     assert b[1, 1] == 13
     b = a[1]
     assert b.shape == (3, 2)
     assert b[2, 1] == 15
     b = a[:, 1]
     assert b.shape == (4, 2)
     assert b[0, 1] == 13
     b = a[:, 1, :]
     assert b.shape == (4, 2)
     assert b[0, 1] == 13
     b = a[1, 2]
     assert b[1] == 15
     b = a[:]
     assert b.shape == (4, 3, 2)
     assert b[1, 2, 1] == 15
     assert b[0, 1, 1] == 13
     b = a[:][:, 1][:]
     assert b[2, 1] == 0.0
     assert b[0, 1] == 13
     raises(IndexError, b.__getitem__, (4, 1))
     assert a[0][1][1] == 13
     assert a[1][2][1] == 15
Пример #26
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.0, 3.0])"
     a = zeros(2002)
     b = a[::2]
     assert repr(b) == "array([0.0, 0.0, 0.0, ..., 0.0, 0.0, 0.0])"
Пример #27
0
 def test_sub_where(self):
     from numpypy import where, ones, zeros, array
     a = array([1, 2, 3, 0, -3])
     v = a.view(self.NoNew)
     b = where(array(v) > 0, ones(5), zeros(5))
     assert (b == [1, 1, 1, 0, 0]).all()
     # where returns an ndarray irregardless of the subtype of v
     assert not isinstance(b, self.NoNew)
Пример #28
0
 def initial(self, init_cond):
     if init_cond == 'null':
         self.field = np.zeros((self.p.Nz, self.p.NFourier))
     elif init_cond == "T":
         self.field = np.array([[T_0(n,k,self.p) for n in range(self.p.NFourier)]
                                for k in range(self.p.Nz)])
     else:
         raise Exception("init_cond must be either `null` or `T`")
Пример #29
0
 def test_init(self):
     from numpypy import zeros
     a = zeros(15)
     # Check that storage was actually zero'd.
     assert a[10] == 0.0
     # And check that changes stick.
     a[13] = 5.3
     assert a[13] == 5.3
Пример #30
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
Пример #31
0
 def test_str_slice(self):
     from numpypy import array, zeros
     a = array(range(5), float)
     b = a[1::2]
     assert str(b) == "[1.0 3.0]"
     a = zeros(2002)
     b = a[::2]
     assert str(b) == "[0.0 0.0 0.0 ..., 0.0 0.0 0.0]"
Пример #32
0
 def test_setslice_of_slice_array(self):
     from numpypy import array, zeros
     a = zeros(5)
     a[::2] = array([9., 10., 11.])
     assert a[0] == 9.
     assert a[2] == 10.
     assert a[4] == 11.
     a[1:4:2][::-1] = array([1., 2.])
     assert a[0] == 9.
     assert a[1] == 2.
     assert a[2] == 10.
     assert a[3] == 1.
     assert a[4] == 11.
     a = zeros(10)
     a[::2][::-1][::2] = array(range(1, 4))
     assert a[8] == 1.
     assert a[4] == 2.
     assert a[0] == 3.
Пример #33
0
 def test_broadcast_scalar(self):
     from numpypy import zeros
     a = zeros((4, 5), 'd')
     a[:, 1] = 3
     assert a[2, 1] == 3
     assert a[0, 2] == 0
     a[0, :] = 5
     assert a[0, 3] == 5
     assert a[2, 1] == 3
     assert a[3, 2] == 0
Пример #34
0
    def test_reduce_errors(self):
        from numpypy import sin, add, maximum, zeros

        raises(ValueError, sin.reduce, [1, 2, 3])
        assert add.reduce(1) == 1

        assert list(maximum.reduce(zeros((2, 0)), axis=0)) == []
        exc = raises(ValueError, maximum.reduce, zeros((2, 0)), axis=None)
        assert exc.value[0] == ('zero-size array to reduction operation '
                                'maximum which has no identity')
        exc = raises(ValueError, maximum.reduce, zeros((2, 0)), axis=1)
        assert exc.value[0] == ('zero-size array to reduction operation '
                                'maximum which has no identity')

        a = zeros((2, 2)) + 1
        assert (add.reduce(a, axis=1) == [2, 2]).all()
        assert (add.reduce(a, axis=(1,)) == [2, 2]).all()
        exc = raises(ValueError, add.reduce, a, axis=2)
        assert exc.value[0] == "'axis' entry is out of bounds"
Пример #35
0
 def test_getsetitem(self):
     import numpypy
     a = numpypy.zeros((2, 3, 1))
     raises(IndexError, a.__getitem__, (2, 0, 0))
     raises(IndexError, a.__getitem__, (0, 3, 0))
     raises(IndexError, a.__getitem__, (0, 0, 1))
     assert a[1, 1, 0] == 0
     a[1, 2, 0] = 3
     assert a[1, 2, 0] == 3
     assert a[1, 1, 0] == 0
     assert a[1, -1, 0] == 3
Пример #36
0
def np_diag(a):
    """Takes a 1-d vector and makes it the diagonal of a 2-d vector
    """
    if ispypy():
        nrows, = a.shape
        n = np.zeros((nrows, nrows))
        for i in xrange(nrows):
            n[i,i] = a[i]
        return n
    else:
        return np.diagonal(a)
Пример #37
0
def np_second_arg_array_index(matrix, array):
    """Calculates matrix[:,array]
    NOTE: THIS APPEARS TO BE VERY BROKEN
    """
    if ispypy():
        nrows,ncols = matrix.shape
        if len(array.shape) == 1:
            n = np.zeros((1, array.shape[0]))
            for i in xrange(array.shape[0]):
                n[0,i] = np.sum(matrix[:,int(array[i])])
            return n
        else:
            assert len(array.shape) == 2
            n = np.zeros(array.shape)
            for i in xrange(array.shape[0]):
                n[i] = np_second_arg_array_index(matrix, array[i])
            return n

    else:
        return matrix[:,array]
Пример #38
0
def lcsLength(line1, line2):
    N = len(line1)
    M = len(line2)
    memo = np.zeros((N + 1, M + 1), dtype=int)
    for i in range(1, N + 1):
        for j in range(1, M + 1):
            if line1[i - 1] == line2[j - 1]:
                memo[i, j] = memo[i - 1, j - 1] + 1
            else:
                memo[i, j] = max(memo[i, j - 1], memo[i - 1, j])
    return memo[N, M]
Пример #39
0
def lcsLength(line1, line2):
    N = len(line1)
    M = len(line2)
    memo = np.zeros((N + 1, M + 1), dtype=int)
    for i in range(1, N + 1):
        for j in range(1, M + 1):
            if line1[i - 1] == line2[j - 1]:
                memo[i, j] = memo[i - 1, j - 1] + 1
            else:
                memo[i, j] = max(memo[i, j - 1], memo[i - 1, j])
    return memo[N, M]
Пример #40
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()
Пример #41
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) == "[]"
Пример #42
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)"
Пример #43
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)
Пример #44
0
    def computeAlignmentMatrix(self, first, second):
        m = len(first) + 1
        n = len(second) + 1
        f = numpy.zeros((m, n), int)
        for i in range(1, m):
            for j in range(1, n):
                # Match elements.
                ab = f[i - 1, j - 1] \
                    + self.scoring(first[i - 1], second[j - 1])

                # Gap on sequenceA.
                ga = f[i, j - 1] + self.gapScore

                # Gap on sequenceB.
                gb = f[i - 1, j] + self.gapScore

                f[i, j] = max(0, max(ab, max(ga, gb)))
        return f
Пример #45
0
def solve(par):
    N, boxes = par
    memo = np.zeros((N, MAXW), dtype=int)

    def dp(idx, remainW):
        if memo[idx, remainW]:
            return memo[idx, remainW]
        if not remainW:
            return 0
        currMax = 1
        for i in range(idx + 1, N):
            if boxes[i][0] <= remainW:
                m1 = dp(i, remainW - boxes[i][0]) + 1
                currMax = max(currMax, m1)
        memo[idx, remainW] = currMax
        return currMax

    return max(dp(i, boxes[i][1]) for i in range(N))
Пример #46
0
    def test_sum(self):
        # tests taken from numpy/core/fromnumeric.py docstring
        from numpypy import sum, ones, zeros, array
        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()
        # If the accumulator is too small, overflow occurs:
        # assert ones(128, dtype=int8).sum(dtype=int8) == -128

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

        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()
Пример #47
0
    def test_sort_order(self):
        from numpypy import array, zeros
        from sys import byteorder
        # Test sorting an array with fields
        skip('not implemented yet')
        x1 = array([21, 32, 14])
        x2 = array(['my', 'first', 'name'])
        x3=array([3.1, 4.5, 6.2])
        r=zeros(3, dtype=[('id','i'),('word','S5'),('number','f')])
        r['id'] = x1
        r['word'] = x2
        r['number'] = x3

        r.sort(order=['id'])
        assert (r['id'] == [14, 21, 32]).all()
        assert (r['word'] == ['name', 'my', 'first']).all()
        assert max(abs(r['number'] - [6.2, 3.1, 4.5])) < 1e-6

        r.sort(order=['word'])
        assert (r['id'] == [32, 21, 14]).all()
        assert (r['word'] == ['first', 'my', 'name']).all()
        assert max(abs(r['number'] - [4.5, 3.1, 6.2])) < 1e-6

        r.sort(order=['number'])
        assert (r['id'] == [21, 32, 14]).all()
        assert (r['word'] == ['my', 'first', 'name']).all()
        assert max(abs(r['number'] - [3.1, 4.5, 6.2])) < 1e-6

        if byteorder == 'little':
            strtype = '>i2'
        else:
            strtype = '<i2'
        mydtype = [('name', 'S5'), ('col2', strtype)]
        r = array([('a', 1), ('b', 255), ('c', 3), ('d', 258)],
                     dtype= mydtype)
        r.sort(order='col2')
        assert (r['col2'] == [1, 3, 255, 258]).all()
        assert (r == array([('a', 1), ('c', 3), ('b', 255), ('d', 258)],
                                 dtype=mydtype)).all()
Пример #48
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()
Пример #49
0
    def computeAlignmentMatrix(self, first, second):
        m = len(first) + 1
        n = len(second) + 1
        f = np.zeros((m, n), int)
        for i in range(1, m):
            for j in range(1, n):
                # Match elements.
                ab = f[i - 1, j - 1] \
                    + self.scoring(first[i - 1], second[j - 1])

                # Gap on first sequence.
                if i == m - 1:
                    ga = f[i, j - 1]
                else:
                    ga = f[i, j - 1] + self.gapScore

                # Gap on second sequence.
                if j == n - 1:
                    gb = f[i - 1, j]
                else:
                    gb = f[i - 1, j] + self.gapScore

                f[i, j] = max(ab, max(ga, gb))
        return f
Пример #50
0
def dp(status, target):
    if memo[status, target] != -1:
        return memo[status, target]
    if target == 0:
        memo[status, target] = 1
        return 1
    for i in range(n):
        if not (status & (1 << i)) and target - w[i] >= 0:
            if dp(status | (1 << i), target - w[i]):
                memo[status, target] = 1
                return 1
    memo[status, target] = 0
    return 0


sys.stdin = open('input.txt')
for _ in range(int(input())):
    w = map(int, raw_input().split())
    s = sum(w)
    n = len(w)
    if s & 1:
        print 'NO'
    else:
        memo = np.zeros((1 << n, s // 2 + 1), dtype=np.byte)
        memo.fill(-1)
        if dp(0, s // 2):
            print 'YES'
        else:
            print 'NO'
Пример #51
0
 def computeAlignmentMatrix(self, first, second):
     return np.zeros(0, int)
Пример #52
0
 def test_alen(self):
     # tests taken from numpy/core/fromnumeric.py docstring
     from numpypy import array, zeros, alen
     a = zeros((7,4,5))
     assert a.shape[0] == 7
     assert alen(a)    == 7
Пример #53
0
print "      subtract_layer  =", subtract_layer
print "      output_binning  =", output_binning
print "      output_mm       =", output_mm
print "      output_base     =", output_base
print "      binned columns  = "+str(num_columns/output_binning)+", binned rows = "+str(num_rows/output_binning)
print " "

# Read image data:
print ' -- Reading input file: ',image_file_name,'...'
mammo = dicom.read_file(image_file_name) 


# Process pixel values:
print '\n Processing pixel values; rows = ',num_rows,', columns = ',num_columns,'...'
sys.stdout.write(' Current row: ');               # Used instead of print bc no new line added after text
pix = numpypy.zeros((rows[1], columns[1]))        # We will work on this copy of the data as floats, init to 0
num_air_pix = 0

conversion_factor = (compression_thickness/log(float(average_breast_intensity/float(air_intensity)))) * (mfp_plastic/mfp_breast) 
# Test1:    conversion_factor = (compression_thickness*log(float(average_breast_intensity))) * (mfp_plastic/mfp_breast)           #   Matthew Clark operation change 7/15/2015
# Original: conversion_factor = (compression_thickness/log(float(average_breast_intensity))) * (mfp_plastic/mfp_breast) 

for j in range(rows[0], rows[1], output_binning):
  sys.stdout.write(str(j)+', '); sys.stdout.flush()
  for i in range(columns[0], columns[1], output_binning):
  
    # If requested, re-bin the output to reduce the print resolution (1=no-binning, 2=average_4pixels...):
    if output_binning>1:
      avg = 0.0
      for k1 in range(0, output_binning):
        for k2 in range(0, output_binning):
Пример #54
0
import time

try:
    import numpypy as numpy
except ImportError:
    import numpy

def pyloop(a):
    sum = 0
    for i in range(len(a)):
        sum += a[i]
    return sum

def c_loop(a):
    return numpy.sum(a)

a = numpy.zeros(10000000)

x = time.clock()
sum1 = pyloop(a)
y = time.clock()
print 'pyloop: %.4f secs' % (y-x)

x = time.clock()
sum2 = c_loop(a)
y = time.clock()
print 'c_loop: %.4f secs' % (y-x)

assert sum1 == sum2
Пример #55
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"
Пример #56
0
sys.stdin = open('input.txt')
case = 0
while True:
    case += 1
    if case != 1:
        try:
            raw_input()
        except:
            break
    m = int(input())
    names = {}
    nameId = []
    for i in range(m):
        nameId.append(raw_input().strip())
        names[nameId[-1]] = i
    edges = np.zeros((m + 1, m + 1), dtype=np.int)
    n = int(input())
    for i in range(n):
        a, b = raw_input().strip().split()
        edges[names[a], names[b]] = 1
    for i in range(m):
        edges[m, i] = 1
    topoResult = []
    visited = [0] * (m + 1)
    dfs(m)
    print 'Case #%d: Dilbert should drink beverages in this order:' % case,
    for i in topoResult[:-1][::-1]:
        print nameId[i],
    print '\n'
Пример #57
0
import sys
import numpypy as np


def dfs(s):
    res = 0
    for t in range(n):
        if graph[s, t] and not visited[s, t]:
            visited[s, t] = visited[t, s] = 1
            res = max(res, dfs(t) + 1)
            visited[s, t] = visited[t, s] = 0
    return res

sys.stdin = open('input.txt')
while True:
    n, m = map(int, raw_input().split())
    if not n and not m:
        break
    graph = np.zeros((n, n), dtype=np.byte)
    visited = np.zeros((n, n), dtype=np.byte)
    for _ in range(m):
        a, b = map(int, raw_input().split())
        graph[a, b] = graph[b, a] = 1
    res = 0
    for i in range(n):
        visited.fill(0)
        res = max(res, dfs(i))
    print res
Пример #58
0
#!/usr/bin/env pypy

import argparse
import numpypy as np
from sys import stdout

max_cnt = 250

ap = argparse.ArgumentParser()
ap.add_argument('reads_fn', metavar = 'reads.fastq')
args = ap.parse_args()

xs = np.zeros(41 * 41, dtype = np.uint64)

f = open(args.reads_fn)
qq = 0
while True:
    id1  = f.readline()
    seq  = f.readline()
    id2  = f.readline()
    qual = f.readline()

    if id1 == '' or seq == '' or id2 == '' or qual == '':
        break

    for q in qual.strip():
        qq = (41 * qq + (ord(q) - 33)) % (41 * 41)
        xs[qq] += 1


for q in xrange(41):
Пример #59
0
    def _add_representative_phrases(self, hierarchy, limit=10):
        # flatten hierarhcy
        clusters = []

        def walk_clusters(h):
            for cluster in h:
                clusters.append(
                    ("%s_%s" % (int(100 * cluster['cutoff']), cluster['name']),
                     cluster))
                walk_clusters(cluster['children'])

        walk_clusters(hierarchy)

        # make a list of clusters for each document
        doc_clusters = defaultdict(list)
        for i, (cluster_id, cluster) in enumerate(clusters):
            for doc in cluster['members']:
                doc_clusters[doc].append(i)

        # grab all the phrases in the corpus and map them to an index
        phrase_dict = {}
        phrases = []
        self.cursor.execute(
            """
            select phrase_id from phrases where corpus_id = %(corpus_id)s
        """, dict(corpus_id=self.sentence_corpus_id))
        for i, (phrase, ) in enumerate(self.cursor):
            phrases.append(phrase)
            phrase_dict[phrase] = i

        # build the tracking array
        cluster_counts = numpy.zeros((len(clusters), len(phrases)), 'f')
        total_counts = numpy.zeros(len(phrases), 'f')

        # grab all the occurrences
        self.cursor.execute(
            """
            select distinct document_id, phrase_id from phrase_occurrences where corpus_id = %(corpus_id)s
        """, dict(corpus_id=self.sentence_corpus_id))

        # iterate over them and do the counting
        empty = []
        for document_id, phrase_id in self.cursor:
            affected_clusters = doc_clusters.get(document_id, empty)
            phrase_offset = phrase_dict[phrase_id]
            total_counts[phrase_offset] += 1.0
            for cluster in affected_clusters:
                cluster_counts[cluster, phrase_offset] += 1.0

        # convert counts into scores
        top_phrases = []
        for i in xrange(len(clusters)):
            scores = cluster_counts[i] / (float(len(clusters[i][1]['members']))
                                          + total_counts - cluster_counts[i])
            phrase_idxs = wirth_n_largest(scores, limit)
            top_phrases.append([phrases[idx] for idx in phrase_idxs])

        all_phrase_ids = tuple(set(itertools.chain.from_iterable(top_phrases)))
        self.cursor.execute(
            """
            select p.phrase_id, substring(text for (p.indexes[1].end - p.indexes[1].start) from p.indexes[1].start + 1)
            from (
                select distinct on (phrase_id) document_id, phrase_id, indexes
                    from phrase_occurrences
                    where
                        corpus_id = %(corpus_id)s
                        and phrase_id in %(phrase_ids)s
                ) p
            inner join documents d on d.corpus_id = %(corpus_id)s and d.document_id = p.document_id
        """, dict(corpus_id=self.sentence_corpus_id,
                  phrase_ids=all_phrase_ids))

        phrase_text = dict(self.cursor.fetchall())

        for i, (cluster_id, cluster) in enumerate(clusters):
            cluster['phrases'] = [
                phrase_text.get(j, "") for j in top_phrases[i]
            ]

        return hierarchy
Пример #60
0
comp4 = [(comp2[x & 0xf] << 4) | comp2[x >> 4] for x in xrange(0x100)]
comp8 = [(comp4[x & 0xff] << 8) | comp4[x >> 8] for x in xrange(0x10000)]


def revcomp(x, k):
    y = (comp8[x & 0xffff] << 48) | \
        (comp8[(x >> 16) & 0xffff] << 32) | \
        (comp8[(x >> 32) & 0xffff] << 16) | \
        (comp8[(x >> 48) & 0xffff])

    return y >> (64 - (2 * k))


N = 4**(args.k + 2)
mask = N - 1
xs = np.zeros(N, dtype=np.uint32)

x = 0
for line in open(args.genome_fn):
    if line[0] == '>':
        stderr.write(line)
        continue
    vs = (nucnum[v] for v in line.strip().upper() if v != 'N')

    for v in vs:
        x = ((x << 2) | v) & mask
        xs[x] += 1
        xs[int(revcomp(x, args.k + 2))] += 1

for x in xrange(4**args.k):
    z = 0