def __init__(self, pars, is_kinetic=False, acc=0, ang_acc=0, fr=0, lives=0, life=0): self.image = pars["image"] self.image_center = pars["info"].get_center() self.image_size = pars["info"].get_size() radius = pars["info"].get_radius() self.up_key_down = False self.left_key_down = False self.right_key_down = False self.missile_image = pars["missile_image"] self.missile_info = pars["missile_info"] self.missile_sound = pars["missile_sound"] self.ship_thrust_sound = pars["ship_thrust_sound"] self.missile_group = set([]) self.lives = lives self.life = life self.score = 0 if is_kinetic: self.physics = Physics(radius, pars["WIDTH"], pars["HEIGHT"], None, is_kinetic, fr) self.physics.set_ang_acc(ang_acc) self.physics.set_acc(acc) else: self.physics = Physics(radius, WIDTH, HEIGHT) self.physics.set_pos(pars["pos"]) self.physics.set_vel(pars["vel"]) self.physics.set_ang(pars["ang"]) self.physics.set_ang_vel(pars["ang_vel"])
def __init__(self, file_root, physics=None, smoothing=0.0, degree=3, SET_GLOBAL_EVOL=True): if physics is None: self.__phys = Physics() else: self.__phys = physics self.__f_data = np.loadtxt(file_root + '_devolution.dat') self.__delta_data = np.loadtxt(file_root + '_evolution.dat') a_data = np.loadtxt(file_root + '_a_vals.dat') self.__a_vals = a_data[:, 0] assert (a_data[-1, 0] == 1.0) self.__k_vals = np.loadtxt(file_root + '_matterpower_out.dat')[:, 0] * self.__phys.h if SET_GLOBAL_EVOL: physics.read_in_H(self.__a_vals, a_data[:, 1] / a_data[-1, 1]) normalized_dataset = self.__delta_data / np.meshgrid( self.__a_vals, self.__delta_data[:, -1])[1] G_interpolation = RectBivariateSpline(np.log10(self.__k_vals), np.log10(self.__a_vals), normalized_dataset, bbox=[ min(np.log10(self.__k_vals)), max(np.log10(self.__k_vals)), min(np.log10(self.__a_vals)), max(np.log10(self.__a_vals)) ], kx=degree, ky=degree, s=smoothing) self.__G_func = lambda a, k: np.squeeze( G_interpolation.ev(np.log10(k), np.log10(a))) f_interpolation = RectBivariateSpline(np.log10(self.__k_vals), np.log10(self.__a_vals), self.__f_data, bbox=[ min(np.log10(self.__k_vals)), max(np.log10(self.__k_vals)), min(np.log10(self.__a_vals)), max(np.log10(self.__a_vals)) ], kx=degree, ky=degree, s=smoothing) self.__f_func = lambda a, k: np.squeeze( f_interpolation.ev(np.log10(k), np.log10(a))) self.__dG_dt = lambda a, k: self.__phys.da_over_a( (1 - a) / a) * np.squeeze( f_interpolation.ev(np.log10(a), np.log10(k))) * self.__G_func( a, k)
def __init__(self, screen): self.screen = screen self.physics = Physics( (0, 0, 1, 1), friction=5000, ) self.imgSize = int(self.screen.get_width() / 4) self.images = [ pygame.transform.scale(pygame.image.load(IMG_DIR + '/' + path), (self.imgSize, self.imgSize)) for path in os.listdir(IMG_DIR) ] # self.currentSelection = int(len(self.images) / 2) self.currentSelection = random.choice(list(range(len(self.images)))) self.surfName = None self.stats = ['attack', 'defense', 'spin'] self.statSurf = pygame.Surface(( int(self.screen.get_width()), int((self.screen.get_height() - self.imgSize) / 2), )) self.startGameWith = None self.UpdateTextSurfaces() self.startTime = time.time()
def __init__(self, init_eta=None, init_upsilon=None, runtime=None, results_interval=300, random_eta_limits=None, random_upsilon_limits=None): '''Initialize parameters Params ====== init_position: 1D numpy array, initial position in x-y-z coordinates (w.r.t. inertial frame) init_orientation: 1D numpy array, initial orientation in phi-theta-psi angles (Z-Y-X Tait-Bryan angles) init_vel: 1D numpy array, initial velocities in x-y-z components (w.r.t. body frame) init_ang_vel: 1D numpy array, initial angle velocities in x-y-z components (w.r.t. body frame) runtime: float, limit simulation time in seconds results_interval: int, iterations between saving results random_position_limits: float list, limits of random position generator random_state_limits: float list, limits of random state generator (orientation, vel and ang_vel) ''' self.labels = [ 'time', 'x', 'y', 'psi', 'x_velocity', 'y_velocity', 'z_angular_velocity', 'Tport', 'Tstbd' ] self.physics = Physics(init_eta, init_upsilon, runtime) self.results_interval = results_interval self.random_eta_limits = [[-2.5, 2.5], [-2.5, 2.5], [ -np.pi, np.pi ]] if random_eta_limits is None else random_eta_limits self.random_upsilon_limits = [[0.0, 0.0], [0.0, 0.0], [ 0.0, 0.0 ]] if random_upsilon_limits is None else random_upsilon_limits self.reset()
def preproc(self, world, game): print 'world %d x %d' % (world.width, world.height) pprint(map(list, zip(*world.tiles_x_y))) print world.waypoints print '=====================' self.navigator = Navigator(world) self.physics = Physics(world, game)
def __init__(self, _main): self.main = _main ## PHYSICS HANDLER ## self.physics = Physics(self) ## LEVEL LOADER ## self.currentLevelName = None self.levelloader = LevelLoader(self) self.currentLevelName = "startLevel2-extra" ## INPUT HANDLER self.input = Input(self) self.movementOption = '1' ## HANDLE PLAYER ## self.isPlayerActive = False self.player = {} self.activePlayerName = "player2" ## Start GuI ## self.gui = Gui(self) self.accept("doStart", self.startGame) ## GAME STATE VARIABLES ## self.isMoving = False self.isFloating = False
def __init__(self, screen_rect): self.wall_group = list() rect = pygame.rect.Rect((0, 0), (10, screen_rect.h)) rect.topright = screen_rect.topright self.wall_group.append(Wall(rect)) rect = pygame.rect.Rect((0, 0), (screen_rect.w, 10)) rect.bottomleft = screen_rect.bottomleft self.wall_group.append(Wall(rect)) rect = pygame.rect.Rect((0, 0), (10, screen_rect.h)) rect.topleft = screen_rect.topleft self.wall_group.append(Wall(rect)) rect = pygame.rect.Rect((0, 0), (screen_rect.w, 10)) rect.topleft = screen_rect.topleft self.wall_group.append(Wall(rect)) self.ball_group = list() for i in range(50): b = Ball((random.randint(0, screen_rect.w), random.randint(0, screen_rect.h))) if not any(Physics.is_circle_collision(b, ball) for ball in self.ball_group): self.ball_group.append(b) self.physics = Physics() self.physics.solids.extend(self.wall_group) self.physics.mobiles.extend(self.ball_group)
def __init__(self, _id, pos=[0, 0], color='#27ae60'): # essentials super(Angel, self).__init__() # import settings self.settings = Settings() # set id self.id = _id # surface and rect self.image = pygame.Surface((200, 200)) pygame.draw.circle(self.image, color, (100, 100), 99) self.image = pygame.transform.scale(self.image, (30, 30)) self.image.fill(color) self.rect = self.image.get_rect() self.rect.x, self.rect.y = pos self.image.set_colorkey('#000000') # movement self.controls = controls[0] self.physics = Physics(self.rect, 1) self.last_state = None self.jumping = False self.air_timer = 0 self.colliding = { 'top': False, 'bottom': False, 'left': False, 'right': False } self.wall = False # additional features self.lives = 3 self.stamina = 10.0 self.capJump = 12
def test_straight_movement(self): me, world, game = load_objects() phys = Physics(world, game) me.speed_x = me.speed_y = 0.0 me.x = 6800.0 me.y = 7834.0 car_state = CarState.from_car(me) car_state.brake = False car_state.engine_power = 1.0 car_state.wheel_turn = 0.0 car_state_350 = CarState( 3.1415926535897931, np.array([-23.8683149170807631, 0.0000000000000029]), 0.0, np.array([4351.0112134403343589, 7834.0000000000000000])) car_state_474 = CarState( 3.1415926535897931, np.array([-29.4477720000775669, 0.0000000000000036]), 0.0, np.array([992.6379800312042789, 7834.0000000000000000])) for i in xrange(181, 475): car_state = phys.calc(car_state) car_state.update_car(car_state) if i == 350: self.assertEqual(car_state, car_state_350) elif i == 474: self.assertEqual(car_state, car_state_474)
def __init__(self,pos_x,pos_y,width = 100,height=20): super().__init__() self.settings = Settings() self.image = pygame.Surface((width,height)) self.image.fill('orange') self.rect = self.image.get_rect() self.rect.x, self.rect.y = pos_x, pos_y self.physics = Physics(self.rect,1000)
def __init__(self, simVars, delta=50, tick=0): self.delta = delta self.simVars = simVars self.map = Map(simVars) self.spawner = Spawner(self) self.tick = tick self.physics = Physics()
def __init__(self, pos, vel, angle, angle_vel, image, info, WIDTH, HEIGHT, sound=None, is_kinetic=False, acc=0, ang_acc=0, fr=0): self.pos = [pos[0], pos[1]] self.vel = [vel[0], vel[1]] self.angle = angle self.angle_vel = angle_vel self.image = image self.image_center = info.get_center() self.image_size = info.get_size() radius = info.get_radius() self.lifespan = info.get_lifespan() self.animated = info.get_animated() #self.age = 0 if sound: sound.rewind() sound.play() if is_kinetic: if self.lifespan == None: self.physics = Physics(radius, WIDTH, HEIGHT, None, is_kinetic, fr) else: self.physics = Physics(radius, WIDTH, HEIGHT, self.lifespan, is_kinetic, fr) self.physics.set_ang_acc(ang_acc) self.physics.set_acc(acc) else: if self.lifespan == None: self.physics = Physics(radius, WIDTH, HEIGHT) else: self.physics = Physics(radius, WIDTH, HEIGHT, self.lifespan) self.physics.set_pos(pos) self.physics.set_vel(vel) self.physics.set_ang(angle) self.physics.set_ang_vel(angle_vel)
def add_type(self, name, drawn_type=None, res_asset_path=None, full_asset_path=None, meta_path=None): # make asset path safe if res_asset_path is not None: res_asset_path = res_asset_path.replace('\\', '/') add_type = DrawnType(name, start_ext_id=self.curr_ext_resource_id, start_sub_id=self.curr_sub_resource_id) # break out for specific node types if drawn_type is not None and drawn_type in self.TYPES: if drawn_type == 'sprite': add_type = Sprite(name, res_asset_path, meta_path=meta_path, start_ext_id=self.curr_ext_resource_id, start_sub_id=self.curr_sub_resource_id) elif drawn_type == 'static': add_type = Static(name, res_asset_path, full_asset_path, self.curr_ext_resource_id, self.curr_sub_resource_id, meta_path=meta_path) elif drawn_type == 'platforms': add_type = Static(name, res_asset_path, full_asset_path, self.curr_ext_resource_id, self.curr_sub_resource_id, meta_path=meta_path, one_way=True) elif drawn_type == 'physics' or drawn_type == 'items': add_type = Physics(name, res_asset_path, meta_path, self.curr_ext_resource_id, self.curr_sub_resource_id) elif res_asset_path is not None: # use sprites, if asset path exists add_type = Sprite(name, res_asset_path, meta_path=meta_path, start_ext_id=self.curr_ext_resource_id, start_sub_id=self.curr_sub_resource_id) # add node, external, sub content self.nodes += add_type.get_node_string() + '\n' self.ext_resources += add_type.get_ext_resources_string() self.sub_resources += add_type.get_sub_resources_string() # update id's self.curr_ext_resource_id = add_type.get_last_ext_id() self.curr_sub_resource_id = add_type.get_last_sub_id()
def __init__(self, name='untiled', pos=MyVector(0, 0, 0), vel=MyVector(0, 0, 0), mesh='untiled.mesh', yaw=0): self.name = name self.pos = pos self.vel = vel self.mesh = mesh self.yaw = yaw self.aspectTypes = ['Physics'] self.aspects = [Physics(self)]
def run_game(): pygame.init() screen_size = (600, 385) screen = pygame.display.set_mode(screen_size) mario = Mario(screen) background = Background(screen, './mario_pics/full_background_no_sky.png', mario) question_block = Block(screen, 300) physics = Physics() # first_goomba = Goomba(screen) enemies = Group() game_on = True tick = 0 background_color = (93, 148, 251) # r = randint(0, 255) # g = randint(0,255) # b = randint(0,255) while game_on == True: # tick += 1 # background_color = (r, g, b) # if tick % 5 == 0: # r += 10 # g += 15 # b += 16 # if r > 230: # r -= 150 # if g > 230: # g -= 150 # if b > 230: # b -= 150 # print tick for i in background.goomba_spawn_points: if background.x == i: enemies.add(Goomba(screen)) check_events(background, mario, question_block, screen) screen.fill(background_color) background.draw_background(mario) mario.draw_mario(physics, background) question_block.draw_block(mario) print enemies for enemy in enemies: enemy.draw_goomba(mario, physics, background) mario.check_mario_is_alive(background, enemy) # first_goomba.draw_goomba(mario) pygame.display.flip()
def __init__(self, _main): self.main = _main # Physics self.physics = Physics(self) # Level self.levelloader = LevelLoader(self) # Input # Player self.player = Player(self) # GUI # STATE self.isFloating = False
def build_level(self, level_file='lvl/level1.lvl'): lvl = Level(level_file) w, h = 100., 100. self.physics = Physics(w, h) # build units hero = self.add_hero(*lvl.units['h'][0]) ball = self.add_ball(*lvl.units['b'][0]) goal = self.add_goal(*lvl.units['g'][0]) units = [hero, ball, goal] self.hero, self.ball, self.goal = hero, ball, goal for sym, target, anim in [('h', hero, 'type1'), ('b', ball, 'type2'), ('g', goal, 'type3')]: for (x, y) in lvl.units['e%s' % sym]: u = self.add_enemy_following_target(x, y, target) u.set_animation(anim) units.append(u) self.units = units # build physics space self.physics.space.add_collision_handler( 3, # goal 4, # ball post_solve=self.game_rules.collision_ball_border, ) # Bind events to actions def on_double_tap(dt, pos): if not self.is_paused: self.add_explosion(hero.get_position()) def on_key_down(dt, key): actions = { 'w': self.hero.move_up, 's': self.hero.move_down, 'a': self.hero.move_left, 'd': self.hero.move_right, 'o': lambda _: self.add_explosion(hero.get_position()), } if key in actions: actions[key](dt) self.event_manager.register_action('double tap', on_double_tap) self.event_manager.register_action('swipe', self.hero.move) self.event_manager.register_action('key down', on_key_down)
def test_calc_brake_distance(self): me, world, game = load_objects() phys = Physics(world, game) car_state = CarState.from_car(me) car_state.wheel_turn = 0.0 car_state.speed = np.array([-27.0311463976256405, 0.0]) speed_limit = 1.8195814109630735 ticks, brake_dist, car_state = phys.calc_brake_distance( car_state, speed_limit) self.assertEqual(ticks, 72) self.assertAlmostEquals(brake_dist, 958.2923150089691262, delta=TestPhysics.EPSILON) self.assertTrue( np.allclose(car_state.speed, np.array([-1.8195814109630735, 0.0]), rtol=0, atol=TestPhysics.EPSILON))
class Game(): physics = Physics() def __init__(self): self.artifact_manager = ArtifactManager() self.hero_manager = HeroManager() def connect_new_gamer(self, id, name): self.hero_manager.add(id, name) return self.hero_manager.get(id) def disconnect_gamer(self, id): self.hero_manager.delete(id) def get_all_artifacts(self): all = [] for a in self.artifact_manager.get_all(): a = a.__dict__ all.append(a) return all def get_all_heroes(self): all = [] for a in self.hero_manager.get_all(): a = a.__dict__ all.append(a) return all def move(self, id, direction): self.hero_manager.move(id, direction) hero = self.hero_manager.get(id) r = {'x': hero.x, 'y': hero.y, 'diameter': hero.diameter, 'eat': None} for artifact in self.artifact_manager.get_all(): if self.physics.object_on_object(hero, artifact): self.hero_manager.eat_artifact(id, artifact) self.artifact_manager.delete(artifact.id) r['eat'] = artifact for another_hero in self.hero_manager.get_all(): if self.physics.object_on_object( hero, another_hero) and another_hero.id != hero.id: self.hero_manager.eat_hero(id, another_hero) self.hero_manager.delete(another_hero.id) r['eat'] = another_hero return r
def __init__(self, config_file=None): """ Method to initialize the Engine class. """ pygame.init() self.running = True self.icon = pygame.image.load("assets/icon.png") self.background = pygame.image.load("assets/background.png") self.score_value = 0 self.screen_text = pygame.font.Font('freesansbold.ttf', 32) self.screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("Space Invaders") pygame.display.set_icon(self.icon) self.player = Player() self.enemy_fleet = EnemyFleet(16) self.enemy_fleet.create_fleet() self.game_physics = Physics()
def __init__(self, period=0.05): """Setup the world, physics and viewer for the simulation.""" # bind the world step rate # - seconds, passed to gui loop self.period = period # - ideal step length, but procees time will vary self.current_dt_target = period # setup the size of the world self.width = DEFAULT_WORLD_M_W self.height = DEFAULT_WORLD_M_H # initialize physics engine self.physics = Physics(self) # create the map manager self.map_manager = MapManager(self) # create the GUI self.viewer = Viewer(self, self.period, DEFAULT_ZOOM, RANDOM) self.viewer.initialise_viewer()
def __init__(self, parameters, history): self.parameters = parameters self.history = history self.physics = Physics(parameters, history) self.helpers = Helpers(parameters, history)
def test_integration1_monster_physics_vel_speed_false(self): monster = Monster() physics = Physics() speed = physics.update_speed(0, 10, 5) monster.velocity = physics.update_velocity(monster.velocity, speed, 0) self.assertNotEqual(monster.velocity, [0, 0, 0])
def main(cfg_file): home_path = '.' cfg_fp = normpath(pjoin('.', 'config', cfg_file)) with open(cfg_fp) as fp: cfg = yaml.load(fp, Loader=yaml.SafeLoader) lt = localtime() y, m, d = lt[0:3] date = '%02i%02i%02i' % (d, m, y) rid = "{:d}".format(np.random.randint(1000)) savename = normpath( pjoin('.', 'Results', 'sim_data_' + date + '_' + rid + '.hdf5')) print(savename) material = cfg["source"]["material"] kVp = cfg["source"]["kVp"] mAs = cfg["source"]["mAs"] eBin = cfg["source"]["eBin"] npx = cfg["detector"]["npx"] npy = cfg["detector"]["npy"] pxpitch = cfg["detector"]["pitch"] SPR = cfg["detector"]["SPR"] SNR = cfg["detector"]["SNR"] bits = cfg["detector"]["bits"] calibration = cfg["detector"]["calibration"] # num_workers = cfg["general"]["nworkers"] n_img = cfg["general"]["nimg"] n_pos = cfg["general"]["npos"] dimx = npx * pxpitch dimy = npy * pxpitch imgs = np.zeros((npx * npy, 0)) shifts = np.zeros((2, 0)) source = Source(cfg['source'], np.array([0, 0, 700]), 0.54, 0.33, home_path) physic = Physics() if cfg["phantom"]["singleCell"]: cdmam = CDMAM_cell(au_diameter=cfg["phantom"]["diam"], au_thickness=cfg["phantom"]["thick"] * 1e-3, pos=np.array([0, 0, 71]), SPR=SPR, home_path=home_path) else: fname = home_path + cfg["phantom"]["file"] cdmam = CDMAMFF(fname=fname, pos=np.array([0, 0, 71]), SPR=SPR, home_path=home_path) for j in range(0, n_pos): xshift = np.random.choice((-1, 1)) * np.random.rand() * pxpitch yshift = np.random.choice((-1, 1)) * np.random.rand() * pxpitch shift = np.vstack((xshift * np.ones((1, n_img)), yshift * np.ones( (1, n_img)))) detector = Detector(npx, npy, np.array([xshift, yshift, 0]), dimx, dimy, bits, calibration, home_path) cdmamXRAY = physic.compute_image(detector, source, 0, cdmam, 0) dset = do_it(n_img=n_img, detector=detector, phantom=cdmam, prim_img=cdmamXRAY, physic=physic, SNR=SNR, path=home_path) # dset = np.zeros((npx*npy,n_img)) imgs = np.concatenate((imgs, dset), axis=1) shifts = np.concatenate((shifts, shift), axis=1) del detector, cdmamXRAY, dset print(str(j + 1) + '/' + str(n_pos) + ' done.') file = h5py.File(savename, "a") dset_img = file.create_dataset("imgdata", data=imgs) dset_img.attrs['Shift'] = shifts dset_img.attrs['Nx'] = npx dset_img.attrs['Ny'] = npy dset_img.attrs['Pitch'] = pxpitch dset_img.attrs['SNR'] = SNR dset_img.attrs['SPR'] = SPR dset_img.attrs['material'] = material dset_img.attrs['kVp'] = kVp dset_img.attrs['mAs'] = mAs dset_img.attrs['eBin'] = eBin dset_img.attrs['NImg'] = imgs.shape[1] create_dicom_from_h5(file) file.close() print('Saved ' + savename)
def main(): print("welcome to this simple monster fighting game") print("monsters will find your position and come towards you") print("when they are close enough, attack\n ") gamePlaying = True numAlive = 3 player = Player() mon1 = Monster() mon1.position = [10,10,10] mon2 = Monster() mon2.position = [20,20,20] mon3 = Monster() mon3.position = [5,5,5] movement = [-5,-5,-5] physics = Physics() follow = Follow() i = 0 # monsters = [mon1, mon2, mon3] while gamePlaying: print("\n*****************************************") print('you are at [0,0,0]') print('you have',player.numAttacks, 'attacks left') print('the monsters are at ') #print pos if mon1.checkAlive(): print(*mon1.position, sep = ", ") if mon2.checkAlive(): print(*mon2.position, sep=", ") if mon3.checkAlive(): print(*mon3.position, sep=", ") print("\n... monsters moving ... \n") i +=1 # attacking choice = input("attack? Y/N: ") if choice == 'Y': player.numAttacks -= 1 which = input("which monster: ") print("\n*****************************************\n") if which == "1": if follow.closeEnough(mon1.position, player.position) and mon1.checkAlive(): mon1.damage() print("you killed a monster!") numAlive -= 1 else: print("you can't attack that one too bad") if which == "2": if follow.closeEnough(mon2.position, player.position) and mon2.checkAlive(): mon2.damage() print("you killed a monster!") numAlive -= 1 else: print("you can't attack that one too bad") if which == "3": if follow.closeEnough(mon3.position, player.position) and mon3.checkAlive(): mon3.damage() print("you killed a monster!") numAlive -= 1 else: print("you can't attack that one too bad") elif choice == 'N': print("no attack used") else: print("wasted turn on invalid entry smh") #updating pos if not follow.closeEnough(mon1.position, player.position): mon1.position = physics.update_position(movement, mon1.position, 1) if not follow.closeEnough(mon2.position, player.position): mon2.position = physics.update_position(movement, mon2.position, 1) if not follow.closeEnough(mon3.position, player.position): mon3.position = physics.update_position(movement, mon3.position, 1) if numAlive == 0 or player.numAttacks == 0: gamePlaying = False if numAlive == 0: print("\n*****************************************") print("congrats you killed them all!") else: print("\n*****************************************") print("ran out of attacks - there are", numAlive, "monsters left") print("better luck next time")
if rank == 0: run_code = "2020-09-01_sharp_k_lin_n=10_stageII" window = mean_pairwise_velocity.SHARP_K stage = STAGE_II run_database = RunDatabaseManager(os.getcwd() + "/camb_db.dat", os.getcwd() + "/mpv_db.dat") axion_masses = np.logspace(-27, -23, 4 * 10 + 1) axion_frac_vals_lin = np.linspace(0.0, 1.0, 15) axion_frac_vals_log = np.logspace(-3, 0.0, 15) axion_frac_vals = np.unique( np.concatenate((axion_frac_vals_lin, axion_frac_vals_log), 0)) phys = Physics(True, True, READ_H=False) OmegaMh2 = phys.Omega0 * phys.h**2 OmegaBh2 = phys.OmegaB * phys.h**2 #defining survey stages sigma_v_vals = [[310.0, 460.0, 560.0], [160.0, 200.0, 230.0], [120.0, 120.0, 120.0, 120.0, 130.0]] minClusterMass = [1.0e14, 1.0e14, 0.6e14] overlap_area = [4000.0, 6000.0, 10000.0] z_bin_no = [3, 3, 5] zmin_vals = [0.1, 0.1, 0.1] zmax_vals = [0.4, 0.4, 0.6] delta_r = 2.0 r_vals = np.arange(20.0, 180.0, delta_r) / phys.h
import pyglet from keyboard import Keyboard from physics import Physics from tweening import Tween # INITIALIZE THE WINDOW window = pyglet.window.Window() # INITIALIZE SUBSYSTEMS physics = Physics() keyboard = Keyboard(window) tween = Tween()
def init_physics(self): self.physics = Physics(player=self.player, level=self.current_level, level_width=TESTLEVEL_WIDTH, level_height=TESTLEVEL_HEIGHT)
def build_tower(self, build_backprop): with tf.variable_scope("Inputs"): # Input placeholders [Batch, Length, X] placeholders = {} placeholders["sequences"] = \ tf.placeholder(tf.float32, [None, None, self.dims["alphabet"]], name="Sequences") placeholders["secondary_structure"] = \ tf.placeholder(tf.float32, [None, None, self.dims["ss"]], name="SecondaryStructure") placeholders["coordinates_target"] = \ tf.placeholder(tf.float32, [None, None, self.dims["coords"]], name="TargetCoordinates") placeholders["lengths"] = \ tf.placeholder(tf.int32, [None], name="SequenceLengths") placeholders["structure_mask"] = \ tf.placeholder(tf.float32, [None, None], name="StructureMask") placeholders["sequences"] = tf.identity(placeholders["sequences"]) placeholders["bptt_log_decay"] = self.bptt_log_decay if self.use_ec: placeholders["couplings"] = tf.placeholder(tf.float32, [None, None, None], name="Couplings") # Optional placeholders default_dropout = tf.constant( self.hyperparams["training"]["dropout"], dtype=tf.float32) placeholders["global_step"] = self.global_step placeholders["training"] = tf.placeholder_with_default( False, (), name="Training") placeholders["dropout"] = tf.placeholder_with_default( default_dropout, (), name="Dropout") placeholders["native_init_prob"] = tf.placeholder_with_default( 0., (), name="NativeInitProb") placeholders["native_unfold_max"] = tf.placeholder_with_default( 0.5, (), name="NativeUnfoldMax") placeholders[ "native_unfold_randomize"] = tf.placeholder_with_default( False, (), name="NativeRandomUnfold") placeholders["langevin_steps"] = tf.placeholder_with_default( self.hyperparams["folding"]["langevin_steps"], (), name="LangevinSteps") placeholders["beta_anneal"] = tf.placeholder_with_default( 1.0, (), name="BetaAnneal") # Update unknown dims dims = self.dims seq_shape = tf.shape(placeholders["sequences"]) dims["batch"] = seq_shape[0] dims["length"] = seq_shape[1] # Keep track of which variables we create prior_vars = tf.trainable_variables() # Build the protein folding engine physics = Physics(placeholders, dims, self.global_step, self.hyperparams) physics.build_graph() tensors = physics.tensors # Build the loss function loss = Loss(placeholders, tensors, dims, self.global_step, self.hyperparams) loss.build_graph() tensors["score"] = loss.tensors["score"] tensors["coarse_target"] = loss.tensors["coarse_target"] new_vars = tf.trainable_variables() params = {} params["score"] = [v for v in new_vars if "Score" in v.name] params["generator"] = [v for v in new_vars if v not in params["score"]] # Parameter accounting for (param_name, param_set) in params.iteritems(): print "Parameter set: " + param_name p_counts = [np.prod(v.get_shape().as_list()) for v in param_set] p_names = [v.name for v in param_set] p_total = sum(p_counts) print " contains " + str(p_total) + " params in " \ + str(len(p_names)) + " tensors" print "\n" # Backpropagate gradients = None train_ops = physics.layers.train_ops + loss.layers.train_ops if build_backprop: with tf.variable_scope("Backprop"): with tf.variable_scope("Generator"): g_loss = tensors["score"] g_vars = params["generator"] + params["score"] g_grads = tf.gradients(g_loss, g_vars) gen_gvs = zip(g_grads, g_vars) gradients, gen_grad_norm = self.clip_gradients(gen_gvs) """ Gradient damping (gamma) adaptation for simulator During simulator roll-outs, backpropgation is damped as gamma = exp(log_decay) X = gamma * X + (1. - gamma) * tf.stop_gradient(X) When gamma=1.0, this behaves in the usual manner. [ Current Heuristic ] When the model is 'stable': slowly raise gamma with log-geometric scaling When the model is 'unstable': rapidly lower gamma with log-linear scaling """ is_stable = tf.logical_and(tf.is_finite(gen_grad_norm), gen_grad_norm < 100.) decay_update = tf.cond(is_stable, lambda: 0.99 * self.bptt_log_decay, lambda: self.bptt_log_decay - 0.01) self.bptt_decay_ops += [ self.bptt_log_decay.assign(decay_update) ] tf.summary.scalar("GradientNorm", gen_grad_norm, collections=["gen_batch", "gen_dense"]) tf.summary.scalar("BPTTLogDecay", self.bptt_log_decay, collections=["gen_batch", "gen_dense"]) return placeholders, tensors, gradients, train_ops
def run(self): # Initialise variables self.physics = False self.physics_engine = Physics(self) self.raw_blocks = None self.running = True self.unflooding = False self.finite_water = False self.queued_blocks = { } # Blocks which need to be flushed into the file. self.create_raw_blocks() # Start physics engine self.physics_engine.start() # Main eval loop while self.running: try: # Pop something off the queue task = self.in_queue.get() # If we've been asked to flush, do so, and say we did. if task[0] is TASK_FLUSH: self.flush() self.out_queue.put([TASK_FLUSH]) # New block? elif task[0] is TASK_BLOCKSET: try: self[task[1]] = task[2] except AssertionError: self.logger.warning( "Tried to set a block at %s in %s!" % (task[1], self.blocks_path)) # Asking for a block? elif task[0] is TASK_BLOCKGET: self.out_queue.put([TASK_BLOCKGET, task[1], self[task[1]]]) # Perhaps physics was enabled? elif task[0] is TASK_PHYSICSOFF: self.logger.debug("Disabling physics on '%s'..." % self.blocks_path) self.disable_physics() # Or disabled? elif task[0] is TASK_PHYSICSON: self.logger.debug("Enabling physics on '%s'..." % self.blocks_path) self.enable_physics() # I can haz finite water tiem? elif task[0] is TASK_FWATERON: self.logger.debug("Enabling finite water on '%s'..." % self.blocks_path) self.finite_water = True # Noes, no more finite water. elif task[0] is TASK_FWATEROFF: self.logger.debug("Disabling finite water on '%s'..." % self.blocks_path) self.finite_water = False # Do they need to do a Moses? elif task[0] is TASK_UNFLOOD: self.logger.debug("Unflood started on '%s'..." % self.blocks_path) self.unflooding = True # Perhaps that's it, and we need to stop? elif task[0] is TASK_STOP: self.logger.debug("Stopping block store '%s'..." % self.blocks_path) self.physics_engine.stop() self.flush() self.logger.debug("Stopped block store '%s'." % self.blocks_path) return # ??? else: raise ValueError("Unknown BlockStore task: %s" % task) except (KeyboardInterrupt, IOError): pass