def test_generator(self): with assert_warns(FutureWarning): hstack((np.arange(3) for _ in range(2))) if sys.version_info.major > 2: # map returns a list on Python 2 with assert_warns(FutureWarning): hstack(map(lambda x: x, np.ones((3, 2))))
def relativeBaseScoreFitness(gs): scores = gs.baseScores() currentPlayer = (gs.nextPlayer-1) % gs.nbPlayers # Remove player score from the scores bestOpponentScore = max(hstack([scores[:currentPlayer],\ scores[currentPlayer+1:]])) return scores[currentPlayer] - bestOpponentScore
def UCT(gameSettings, rootstate, itermax, verbose=False): """ Conduct a UCT search for itermax iterations starting from rootstate. Return the best move from the rootstate. Assumes 2 alternating players (player 1 starts), with game results in the range [0.0, 1.0].""" rootnode = Node(gameSettings, state = rootstate) for _ in xrange(itermax): node = rootnode state = rootstate.clone() # Select # while node is fully expanded and non-terminal while node.untriedMoves == [] and node.childNodes != []: node = node.UCTSelectChild() state.playMove(node.move) # Expand # if we can expand (i.e. state/node is non-terminal) if node.untriedMoves != []: m = random.choice(node.untriedMoves) state.playMove(m) node = node.AddChild(m,state) # add child and descend tree # Rollout # while state is non-terminal while not state.isOver(): state.playMove(random.choice(state.legalMoves())) # Backpropagate # backpropagate from the expanded node and work back to the root node while node != None: scores = state.finalScores() bestOpponentScore = max(hstack([scores[:node.playerJustMoved],\ scores[node.playerJustMoved+1:]])) diffScore = scores[node.playerJustMoved] - bestOpponentScore # state is terminal. Update node with result # from POV of node.playerJustMoved node.Update( diffScore ) node = node.parentNode # Output some information about the tree - can be omitted if verbose: print rootnode.TreeToString(0) print rootnode.ChildrenToString() # return the move that was most visited return sorted(rootnode.childNodes, key = lambda c: c.visits)[-1].move
def roots(p): """ Return the roots of a polynomial with coefficients given in p. The values in the rank-1 array `p` are coefficients of a polynomial. If the length of `p` is n+1 then the polynomial is described by:: p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Parameters ---------- p : array_like Rank-1 array of polynomial coefficients. Returns ------- out : ndarray An array containing the complex roots of the polynomial. Raises ------ ValueError When `p` cannot be converted to a rank-1 array. See also -------- poly : Find the coefficients of a polynomial with a given sequence of roots. polyval : Evaluate a polynomial at a point. polyfit : Least squares polynomial fit. poly1d : A one-dimensional polynomial class. Notes ----- The algorithm relies on computing the eigenvalues of the companion matrix [1]_. References ---------- .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*. Cambridge, UK: Cambridge University Press, 1999, pp. 146-7. Examples -------- >>> coeff = [3.2, 2, 1] >>> np.roots(coeff) array([-0.3125+0.46351241j, -0.3125-0.46351241j]) """ # If input is scalar, this makes it an array p = atleast_1d(p) if len(p.shape) != 1: raise ValueError("Input must be a rank-1 array.") # find non-zero array entries non_zero = NX.nonzero(NX.ravel(p))[0] # Return an empty array if polynomial is all zeros if len(non_zero) == 0: return NX.array([]) # find the number of trailing zeros -- this is the number of roots at 0. trailing_zeros = len(p) - non_zero[-1] - 1 # strip leading and trailing zeros p = p[int(non_zero[0]):int(non_zero[-1]) + 1] # casting: if incoming array isn't floating point, make it floating point. if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)): p = p.astype(float) N = len(p) if N > 1: # build companion matrix and find its eigenvalues (the roots) A = diag(NX.ones((N - 2, ), p.dtype), -1) A[0, :] = -p[1:] / p[0] roots = eigvals(A) else: roots = NX.array([]) # tack any zeros onto the back of the array roots = hstack((roots, NX.zeros(trailing_zeros, roots.dtype))) return roots
def roots(p): """ Return the roots of a polynomial with coefficients given in p. The values in the rank-1 array `p` are coefficients of a polynomial. If the length of `p` is n+1 then the polynomial is described by:: p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Parameters ---------- p : array_like Rank-1 array of polynomial coefficients. Returns ------- out : ndarray An array containing the complex roots of the polynomial. Raises ------ ValueError : When `p` cannot be converted to a rank-1 array. See also -------- poly : Find the coefficients of a polynomial with a given sequence of roots. polyval : Evaluate a polynomial at a point. polyfit : Least squares polynomial fit. poly1d : A one-dimensional polynomial class. Notes ----- The algorithm relies on computing the eigenvalues of the companion matrix [1]_. References ---------- .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*. Cambridge, UK: Cambridge University Press, 1999, pp. 146-7. Examples -------- >>> coeff = [3.2, 2, 1] >>> np.roots(coeff) array([-0.3125+0.46351241j, -0.3125-0.46351241j]) """ # If input is scalar, this makes it an array p = atleast_1d(p) if len(p.shape) != 1: raise ValueError("Input must be a rank-1 array.") # find non-zero array entries non_zero = NX.nonzero(NX.ravel(p))[0] # Return an empty array if polynomial is all zeros if len(non_zero) == 0: return NX.array([]) # find the number of trailing zeros -- this is the number of roots at 0. trailing_zeros = len(p) - non_zero[-1] - 1 # strip leading and trailing zeros p = p[int(non_zero[0]):int(non_zero[-1])+1] # casting: if incoming array isn't floating point, make it floating point. if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)): p = p.astype(float) N = len(p) if N > 1: # build companion matrix and find its eigenvalues (the roots) A = diag(NX.ones((N-2,), p.dtype), -1) A[0, :] = -p[1:] / p[0] roots = eigvals(A) else: roots = NX.array([]) # tack any zeros onto the back of the array roots = hstack((roots, NX.zeros(trailing_zeros, roots.dtype))) return roots
def test_2D_array(self): a = array([[1],[2]]); b = array([[1],[2]]); res=hstack([a,b]) desired = array([[1,1],[2,2]]) assert_array_equal(res,desired)
def test_1D_array(self): a = array([1]); b = array([2]); res=hstack([a,b]) desired = array([1,2]) assert_array_equal(res,desired)
def test_0D_array(self): a = array(1) b = array(2) res = hstack([a, b]) desired = array([1, 2]) assert_array_equal(res, desired)
def buff_ptsalpha(points, alpha): return np.hstack(( np.array([tuple(p) for p in points], 'f4'), np.array(alpha, 'f4', ndmin=2).transpose(), ))
def __init__(self, scene, points, transpfaces, opaqfaces, lines, color): ctx = scene.ctx self.color = fvec3(color or settings.display['schematics_color']) self.box = boundingbox(points).cast(fvec3) def load(scene): return scene.ctx.program( vertex_shader=open(ressourcedir + '/shaders/uniformcolor.vert').read(), fragment_shader=open(ressourcedir + '/shaders/uniformcolor.frag').read(), ) self.uniformshader = scene.ressource('shader_uniformcolor', load) def load(scene): return scene.ctx.program( vertex_shader=open(ressourcedir + '/shaders/glowenvelope.vert').read(), fragment_shader=open(ressourcedir + '/shaders/glowenvelope.frag').read(), ) self.transpshader = scene.ressource('shader_glowenvelope', load) self.identshader = scene.ressource('shader_ident') normals = Mesh(points, transpfaces).vertexnormals() #print('normals', normals) self.vb_vertices = ctx.buffer( np.hstack(( np.array([tuple(v) for v in points], dtype='f4', copy=False), np.array([tuple(v) for v in normals], dtype='f4'), ))) if transpfaces: self.vb_transpfaces = ctx.buffer( typedlist_to_numpy(transpfaces, dtype='u4')) self.va_transpfaces = ctx.vertex_array( self.transpshader, [(self.vb_vertices, '3f4 3f4', 'v_position', 'v_normal')], self.vb_transpfaces, ) self.va_ident_faces = ctx.vertex_array( self.identshader, [(self.vb_vertices, '3f4 12x', 'v_position')], self.vb_transpfaces, ) else: self.vb_transpfaces = None if opaqfaces: self.vb_opaqfaces = ctx.buffer( typedlist_to_numpy(opaqfaces, dtype='u4')) self.va_opaqfaces = ctx.vertex_array( self.uniformshader, [(self.vb_vertices, '3f4 12x', 'v_position')], self.vb_opaqfaces, ) else: self.vb_opaqfaces = None if lines: self.vb_lines = ctx.buffer(typedlist_to_numpy(lines, dtype='u4')) self.va_lines = ctx.vertex_array( self.uniformshader, [(self.vb_vertices, '3f4 12x', 'v_position')], self.vb_lines, ) self.va_ident_lines = ctx.vertex_array( self.identshader, [(self.vb_vertices, '3f4 12x', 'v_position')], self.vb_lines, ) else: self.vb_lines = None
def test_generator(self): with assert_warns(FutureWarning): hstack((np.arange(3) for _ in range(2))) with assert_warns(FutureWarning): hstack(map(lambda x: x, np.ones((3, 2))))
def test_0D_array(self): a = array(1); b = array(2); res=hstack([a,b]) desired = array([1,2]) assert_array_equal(res,desired)
def roots(p): """ Return the roots of a polynomial with coefficients given in p. The values in the rank-1 array `p` are coefficients of a polynomial. If the length of `p` is n+1 then the polynomial is described by p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Parameters ---------- p : array_like of shape(M,) Rank-1 array of polynomial co-efficients. Returns ------- out : ndarray An array containing the complex roots of the polynomial. Raises ------ ValueError: When `p` cannot be converted to a rank-1 array. Examples -------- >>> coeff = [3.2, 2, 1] >>> print np.roots(coeff) [-0.3125+0.46351241j -0.3125-0.46351241j] """ # If input is scalar, this makes it an array p = atleast_1d(p) if len(p.shape) != 1: raise ValueError,"Input must be a rank-1 array." # find non-zero array entries non_zero = NX.nonzero(NX.ravel(p))[0] # Return an empty array if polynomial is all zeros if len(non_zero) == 0: return NX.array([]) # find the number of trailing zeros -- this is the number of roots at 0. trailing_zeros = len(p) - non_zero[-1] - 1 # strip leading and trailing zeros p = p[int(non_zero[0]):int(non_zero[-1])+1] # casting: if incoming array isn't floating point, make it floating point. if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)): p = p.astype(float) N = len(p) if N > 1: # build companion matrix and find its eigenvalues (the roots) A = diag(NX.ones((N-2,), p.dtype), -1) A[0, :] = -p[1:] / p[0] roots = eigvals(A) else: roots = NX.array([]) # tack any zeros onto the back of the array roots = hstack((roots, NX.zeros(trailing_zeros, roots.dtype))) return roots
def test_1D_array(self): a = array([1]) b = array([2]) res = hstack([a, b]) desired = array([1, 2]) assert_array_equal(res, desired)
def test_2D_array(self): a = array([[1], [2]]) b = array([[1], [2]]) res = hstack([a, b]) desired = array([[1, 1], [2, 2]]) assert_array_equal(res, desired)
def test_casting_and_dtype_type_error(self): a = np.array([1, 2, 3]) b = np.array([2.5, 3.5, 4.5]) with pytest.raises(TypeError): hstack((a, b), casting="safe", dtype=np.int64)