def __init__(self, kernel_class, window_size): super(SVM, self).__init__(kernel_class, window_size) self.debug = False self.cycles = 0 # timers self.t_migrate = t.Timing() self.t_updatek = t.Timing() self.t_move = t.Timing() self.t_q = t.Timing() self.t_learn = t.Timing() self.t_hdr = t.Timing() self.t_h = t.Timing() self.t_loop = t.Timing() self.t_end = t.Timing()
from OpenGL.GL import * import timing timings = timing.Timing() import numpy as np from vector import Vec def addRect(num, pmin, pmax, spacing): #Create a rectangle with at most num particles in it. The size of the return #vector will be the actual number of particles used to fill the rectangle print "**** addRect ****" xmin = pmin.x # * scale xmax = pmax.x # * scale ymin = pmin.y # * scale ymax = pmax.y # * scale print "min, max", xmin, xmax, ymin, ymax rvec = np.ndarray((num, 4), dtype=np.float32) i = 0 for y in np.arange(ymin, ymax, spacing): for x in np.arange(xmin, xmax, spacing): if i >= num: break #print "x, y", x, y rvec[i, 0] = x rvec[i, 1] = y rvec[i, 2] = 0. rvec[i, 3] = 1. i += 1
def main(): C = 100. # electricity #C = 10. # circles device = torch.device('cpu') #device = torch.device('cuda') #d, m = torch.load('data/KDDCup1999.pt'), 2 #d, m = torch.load('data/electricity.pt'), 2 #d, m = torch.load('data/circles/circles.pt'), 2 d, m = torch.load('data/covertype.pt'), 2 x_train, y_train = d['x'][:m], d['y'][:m] svm, vectors = reinit(x_train, y_train, device, C, window_size=WINDOW_SIZE) # maximum number of vectors to be kept in the window #window_width = 125 #window_width = 155 # electricity #window_width = 300 # covertype #window_width = 100 # circles #window_width = 1000 window_width = WINDOW_SIZE svm.debug = False svm.init_statistics() set_len = 50 file = open('running.csv', 'w') timer = t.Timing() for v in range(2, d['x'].shape[0]): # x_set, y_set = d['x'][v:v+set_len].double().to(device), d['y'][v:v+set_len].double().to(device) # x, y = x_set[0], y_set[0].unsqueeze(0) x, y = d['x'][v].double().to(device), d['y'][v].double().to(device).unsqueeze(0) if v > 3000: break if v == window_width: timer.reset() svm.reset_timers() print('Timers were reset') # learn vector v to 0.5 if v % 100 == 0: print(f'>> adding {v} vector with {C/2}') if timer.count > 0: print(f'average time: {timer.get_mean()} s, std: {timer.get_std()} s') svm.append(v, x, y, c_init=C/2) # svm.update_kernel() svm.show_state(False) # before learning the vector, show how it is classified #svm.collect_statistics(file, v, x_set, y_set) # first, check if contribution of this vector is identical # with other's vector already added res = svm.detect_similar(svm.compute_q()) if res: svm.remove() print(f'>> removing {v} vector as duplicate') svm.update_kernel() svm.show_state(False) continue last = svm.rest_set[-1] assert last == v i, c = last, C/2 # print(f'>> learn {i} vector to {c}') try: timer.start() svm.learn(i, c) timer.stop() except SingularMatrixException as e: print(f'>> exception: {e}') print(f'>> removing {last} vector as singular') c = 0.0 svm.unlearn(i, c) continue # svm.show_state() # prepare unlearning first = min(svm.support_set) if svm.rest_set is None or len(svm.rest_set) == 0 else min(min(svm.rest_set), min(svm.support_set)) if len(svm.support_set) + len(svm.rest_set) >= window_width: i, c = first, C/2 # print(f'>> unlearn {i} vector to {c}') if i not in svm.support_set and i not in svm.rest_set: print(f'>> vector {i} already unlearned') continue # timer.start() svm.unlearn(i, c) # timer.stop() # svm.show_state() # second phase of learning i, c = last, C # print(f'>> learn {i} vector to {c}') if i not in svm.support_set and i not in svm.rest_set: print(f'>> vector {i} already unlearned') continue try: timer.start() svm.learn(i, c) timer.stop() except SingularMatrixException as e: print(f'>> exception: {e}') print(f'>> removing {last} vector as singular') c = 0.0 svm.unlearn(i, c) continue # svm.show_state() # second phase of unlearning if len(svm.support_set) + len(svm.rest_set) >= window_width: i, c = first, 0.0 # print(f'>> unlearn {i} vector to {c}') if svm.prevent_unlearn(i): print(f'>> cannot unlearn {i}, it is the only of its class') continue if i not in svm.support_set and i not in svm.rest_set: print(f'>> vector {i} already unlearned') continue try: # timer.start() svm.unlearn(i, c) # timer.stop() except NoOppositeClassLeftException as e: c = C/2 # as previous svm.learn(i, c, revert=True) # svm.show_state() svm.print_timers() file.close() svm.show_state(force=True)
#from OpenGL.GL import GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW, glFlush from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.raw.GL.VERSION.GL_1_5 import GL_DYNAMIC_DRAW, GL_ARRAY_BUFFER import pyopencl as cl import sys import timing tim = timing.Timing() import numpy class Part2(object): def __init__(self, num, dt, *args, **kwargs): self.clinit() self.loadProgram("part2_rk.cl") #self.init_powers() self.num = num self.dt = numpy.float32(dt) self.tim = tim def init_powers(self): mf = cl.mem_flags self.powers_buf = cl.Buffer(self.ctx, mf.WRITE_ONLY, 2**30) self.program.init_powers(self.queue, (2**26, ), None, self.powers_buf) #cl.enqueue_copy(self.queue,self.powers,self.powers_buf) def loadData(self, pos_vbo, col_vbo, vel):
def start(): timer = timing.Timing() board = draw.Board(constants.length, constants.height) board.prepare() # bus.write_line(board.draw()) gametime = float(time.time()) balltime = gametime updateTime = 1 timeToNextUpdate = 0 serving = False serves = 0 playerTwoIsServing = False playerOneBig = True playerTwoBig = True playerOneCanBig = True playerTwoCanBig = True gameOver = False speed = constants.speed[0] # currentNum = 0 # Bat and ball default positions playerOnePos = constants.height // 2 playerTwoPos = constants.height // 2 playerOneScore = 0 playerTwoScore = 0 ballPos = [3, constants.height // 2] # ballMovement ballDirectionX = 1 ballDirectionY = 0 board.clear() board.updateScore(0) board.updateScore(0, True) board.updateBats(playerOnePos, playerTwoPos, playerOneBig, playerTwoBig) board.updateBall(ballPos[0], ballPos[1]) # Infinite loop, maybe? Probably just stop it if a score reaches 10 # Remember, game logic is stored in this file. So we have the REAL pos of the bats/ball here. while True: # Our game clock. Our tickrate is around 13.3, meaning we update our game that many times per sec. currentTime = float(time.time()) timer.update_time() # Checking if we should tick if currentTime - gametime >= 1 / constants.tickrate: # The process is update game time, update bats (size first, THEN movement), # update ball, check if ball is at edge. # If yes, update score, if we won then yay. Otherwise reset positions, push "game time" # forwards by 2 secs to freeze game. THEN we do serve logic until served # regardless: clear board, initialise board, draw scores, draw bats, draw ball. gametime = currentTime # currentNum = (currentNum + 1) % 10 # bus.write_line(currentNum) # board.updateScore(currentNum) # Emulating random button press for big bat if random.randint(0, 250) == 9: if playerOneBig or playerOneCanBig: playerOneBig = not playerOneBig playerOneCanBig = False if random.randint(0, 250) == 9: if playerTwoBig or playerTwoCanBig: playerTwoBig = not playerTwoBig playerTwoCanBig = False # Emulating random bat movement. playerOneMove = random.randint(-1, 1) playerTwoMove = random.randint(-1, 1) playerOnePos += playerOneMove playerTwoPos += playerTwoMove # We wanna make sure our midpoint doesn't mean we're outside our game. # So anything below 2 becomes 2, anything above 22 becomes 22. If big bats then 3 < x < 24 # bats are 1x3 despite image making them look 1x4. Regardless, # this makes things easier. Take pos to be the midpoint. if playerOnePos < (3 if playerOneBig else 2): playerOnePos = (3 if playerOneBig else 2) elif playerOnePos > (20 if playerOneBig else 22): playerOnePos = (20 if playerOneBig else 22) if playerTwoPos < (3 if playerTwoBig else 2): playerTwoPos = (3 if playerTwoBig else 2) elif playerTwoPos > (20 if playerTwoBig else 22): playerTwoPos = (20 if playerTwoBig else 22) if serving: ballPos = [constants.length - 4, playerTwoPos ] if playerTwoIsServing else [3, playerOnePos] # emulating random serve if random.randrange(0, 100) == 9: ballDirectionY = random.randrange(-1, 1, 2) ballDirectionX = -1 if playerTwoIsServing else 1 serving = False serves += 1 if serves == 5: serves = 0 playerTwoIsServing = not playerTwoIsServing else: # Move our ball. if currentTime - balltime >= speed: balltime = currentTime ballPos = [ ballPos[0] + ballDirectionX, ballPos[1] + ballDirectionY ] # check if we hit the top or bottom, reverse ballDirY if ballPos[1] == 0 or ballPos[1] == constants.height - 1: ballDirectionY *= -1 # check if ball has hit bat, so calc next speed/direction if ballPos[0] == 2 or ballPos[0] == constants.length - 3: print("true") # nested if looks nicer # Can confirm deltaOne = playerOnePos - ballPos[1] deltaTwo = playerTwoPos - ballPos[1] if (-2 if playerOneBig else -1) <= deltaOne <= (3 if playerOneBig else 1): print("hit right bat") # set our direction depending whether we hit top, middle, bottom (random right now) if deltaOne < 0: ballDirectionY = -1 elif deltaOne > 0: ballDirectionY = 1 else: ballDirectionY = 0 ballDirectionX *= -1 speed = random.choice(constants.speed) elif (-2 if playerTwoBig else -1) <= deltaTwo <= (3 if playerTwoBig else 1): print("hit left bat") if deltaTwo < 0: ballDirectionY = -1 elif deltaTwo > 0: ballDirectionY = 1 else: ballDirectionY = 0 ballDirectionX *= -1 speed = random.choice(constants.speed) board.prepare() board.updateBats(playerOnePos, playerTwoPos, playerOneBig, playerTwoBig) board.updateBall(ballPos[0], ballPos[1]) # check if ball is at left/right edge, increase score, next serve. if ballPos[0] == 0: playerTwoScore += 1 serving = True playerOnePos = constants.height // 2 playerTwoPos = constants.height // 2 elif ballPos[0] == constants.length - 1: playerOneScore += 1 serving = True playerOnePos = constants.height // 2 playerTwoPos = constants.height // 2 board.updateScore(playerOneScore) board.updateScore(playerTwoScore, True) # check if score is more than 9, win game. if playerOneScore > 9: board.updateWinner() gameOver = True elif playerTwoScore > 9: gameOver = True board.updateWinner(True) # os.system("cls") board.draw() timeToNextUpdate = updateTime - (currentTime - gametime) timer.wait_for_update() if gameOver: break