def points_from_comp(agent_1, agent_2, source_num, order_1, order_2): results = run_sim(agent_1, agent_2) if results[order_1] - results[order_2] > 1: scores[source_num] += 1 / (n * 2) elif 0 < results[order_2] - results[order_2] < 1: scores[source_num] += 0.333 / (n * 2)
def points_from_comp(i, j): results = run_sim(agents[i], agents[j]) if results[0] - results[1] > 1: scores[i] += 1 / ((n - 1) * 2) if i >= n - tested_group_size > j: wins_against_baseline[i] += 1 elif results[1] - results[0] > 1: scores[j] += 1 / ((n - 1) * 2) if j >= n - tested_group_size > i: wins_against_baseline[j] += 1 else: scores[j] += 0.333 / ((n - 1) * 2) scores[i] += 0.333 / ((n - 1) * 2)
dic = eval(open('parameters.py').read()) # Fit true flat-field only once dic['best_fit_params'] = analysis.best_fit_ff( dic['FoV'], dic['ff_samples'], dic['flat_field_order'], dic['stop_condition'], dic['max_iterations'], verbose=dic['verbose']) # Create parameter list parameter_dictionaries = [] for srvy in survey_files: dic['survey_file'] = srvy + '.txt' dic['data_dir'] = srvy parameter_dictionaries.append(dic.copy()) # Perform simulations if multi_proc: os.nice(19) from multiprocessing import Pool p = Pool(processes=multi_proc) results = p.map(simulation.run_sim, parameter_dictionaries) else: results = [] for params in parameter_dictionaries: results.append(simulation.run_sim(params)) print('Simulation Complete!')
parameter_dictionaries = [] dirs = [] for density in density_of_sources: dic['density_of_stars'] = density dic['data_dir'] = '{0:.3f}'.format(density) dirs.append('{0:.3f}'.format(density)) parameter_dictionaries.append(dic.copy()) if multi_proc: os.nice(19) from multiprocessing import Pool p = Pool(processes=multi_proc) p.map(simulation.run_sim, parameter_dictionaries) else: for params in parameter_dictionaries: simulation.run_sim(params) # Read timings from individual directories density = np.zeros(len(dirs)) time_measurement = np.zeros(len(dirs)) time_self_cal = np.zeros(len(dirs)) for indx in range(len(dirs)): f = open(dirs[indx] + '/timings.txt', 'r') density[indx] = float(dirs[indx]) time_measurement[indx] = float(f.readline() .strip('Measurement Catalog (s): ')) time_self_cal[indx] = float(f.readline() .strip('Self-Calibration (s): ')) fig = plt.figure(figsize=(6, 6))
def ch01(): intro = ['\nAfter logging in, you consider your options.', '\nWhat do you do?'] ddisplay.print_text(intro) nosebook = False email = False again = ['\nNo, no, no, that\'s not a valid choice. Try again!'] while True: menu = ['1 - See what\'s happening on Nosebook.', '2 - Check your email.', '3 - Do the work they\'re paying you to be here for.'] ddisplay.print_text(menu) choice = raw_input("Pick one:") try: if int(choice) == 1: if nosebook: print '\nYeah... still a lot of nosebook-picking going on here.' else: ddisplay.print_from_file("resources/story/ch01/ch01_nosebook.txt") nosebook = True elif int(choice) == 2: if email: print '\nNo new email. Alas.' else: print '\nEarlobe enlargement? Wow, they\'ll try anything these days.' email = True elif int(choice) == 3: ddisplay.print_from_file("resources/story/ch01/ch01_work.txt") while True: menu = ['\nWhat do you do?', '1 - Review the manual again to stave off the inevitable. [How to Play]', '2 - Just do it.'] ddisplay.print_text(menu) choice = raw_input("Pick one:") try: if int(choice) == 1: instructions() elif int(choice) == 2: workplacesToBe = [] workplacesToBe.append(workclass.WorkplaceToBe(7, True, workclass.Farm, "FARM #216", "A216")) workplacesToBe.append(workclass.WorkplaceToBe(5, True, workclass.Factory, "FACTORY #139", "C139")) workplacesToBe.append(workclass.WorkplaceToBe(2, False, workclass.Unassigned, "UNASSIGNED", "NONE")) run_sim(workplacesToBe, 2, '#135466') break else: print 'Try again, please. Invalid input.' except ValueError: choice = 0 print 'Try again, please. Invalid input.' break else: ddisplay.print_text(again) except ValueError: choice = 0 ddisplay.print_text(again) print '\nWhat do you do next?' lunch = ['You yawn and stretch. Coffee time is past. It\'s snack time now.', '\nWhoops!', '\nApparently you meant lunch time.'] ddisplay.print_text(lunch) choice = 0 again = ['\nYou... wait, what?! Try that again.'] while (int(choice) != 1) and (int(choice) != 2): chc1 = ['\nWhere do you want to go?', '1 - The good old cafeteria. Mediocre free food, decent conversation.', '2 - Home. Sandwiches and solitude.'] ddisplay.print_text(chc1) choice = raw_input("Pick one:") try: if int(choice) == 1: ddisplay.print_from_file("resources/story/ch01/ch01_cafeteria.txt") elif int(choice) == 2: ddisplay.print_from_file("resources/story/ch01/ch01_home.txt") else: ddisplay.print_text(again) except ValueError: choice = 0 ddisplay.print_text(again) raw_input('\n(Press enter key to continue)')
# directory and then used to generate plots. # Make Python 3 compatible from __future__ import division, print_function # Standard Modules import os import sys # Add simulator modules to Python path sys.path.append('./../..') # Custom Modules import simulation dic = eval(open('parameters.py').read()) results = simulation.run_sim(dic) if dic['data_dir']: os.system('./../../plot.py {0}'.format(dic['data_dir'])) print('Final Fitted Solution:') print('======================') print('Self-Calibration Iterations to Converge: {0:.5}'.format(results[0])) print('RMS Source Error: {0:.5} %'.format(results[1])) print('Instrument Response Badness: {0:.5} %'.format(results[2])) print('Instrument Response Best-in-Basis Badness: {0:.5} %'.format(results[3])) print('Chi2 of Fit: {0:.5}'.format(results[4]))
def ch02(): """ Returns True if Dave is still in player's life at end of module or False otherwise. """ ddisplay.print_from_file("resources/story/ch02/ch02_intro.txt") choice = 0 while (int(choice) != 1) and (int(choice) != 2): opts = ['\n1 - Yeah... that\'s so out of character I can only assume aliens', ' are involved.', '2 - Nah. Dave\'s a great guy but it\'s nice not to have to deal', ' with his peppy peppiness sometimes.'] ddisplay.print_text(opts) choice = raw_input("Pick one:") try: if int(choice) == 1: dave = True ddisplay.print_from_file("resources/story/ch02/ch02_look.txt") elif int(choice) == 2: dave = False print '\nYou sip your coffee obtained in quiet and log in.' else: print '\nDrink some of your coffee and try that again.' except ValueError: choice = 0 print '\nDrink some of your coffee and try that again.' intro = ['Confronted with the usual options...', '\nWhat do you do?'] ddisplay.print_text(intro) #Goof off or work. nosebook = False email = False while True: opts = ['1 - See what\'s happening on Nosebook.', '2 - Check your email.'] if dave: opts.append('3 - Work. Maybe it\'ll take your mind off things.') else: opts.append('3 - Do the work they\'re paying you to be here for.') ddisplay.print_text(opts) choice = raw_input("Pick one:") try: if int(choice) == 1: if nosebook: if dave: noseSeen = ['\nEven scoffing at the nosebook-picking can\'t cheer you up.', 'The term "nosebook-picking" isn\'t even funny right now.'] else: noseSeen = ['\nMore nosebook-picking. Ah, nosebook-picking.', 'Just the term makes you happy. How do you visualize that?'] ddisplay.print_text(noseSeen) else: ddisplay.print_from_file("resources/story/ch02/ch02_nosebook.txt") if dave: print('\nThis isn\'t helping.') else: print('\nYou should probably work. Probably.') nosebook = True elif int(choice) == 2: if email: if dave: print('\nNo new email. Not that you did a good job reading the first two.') else: print('\nNo new email. Who\'s surprised?') else: newEmail = ['\nSomething from Biggs about a party... don\'t care right now.', 'And... news. Noone cares about that.'] ddisplay.print_text(newEmail) email = True elif int(choice) == 3: #Working. while True: opts = ['\nWhat do you do?', '1 - Review the manual again.'] if dave: opts.append('2 - Work. Or try to.') else: opts.append('2 - Work! It\'s like a crummy party you get paid to attend.') ddisplay.print_text(opts) choice = raw_input("Pick one:") try: if int(choice) == 1: instructions() elif int(choice) == 2: workplacesToBe = [] workplacesToBe.append(workclass.WorkplaceToBe(7, True, workclass.Farm, "FARM #512", "A512")) workplacesToBe.append(workclass.WorkplaceToBe(5, True, workclass.Factory, "FACTORY #110", "C110")) workplacesToBe.append(workclass.WorkplaceToBe(6, True, workclass.Factory, "FACTORY #112", "C112")) workplacesToBe.append(workclass.WorkplaceToBe(4, False, workclass.Unassigned, "UNASSIGNED", "NONE")) run_sim(workplacesToBe, 4, '#187949') break else: print 'Try again, please. Invalid input.' except ValueError: choice = 0 print 'Try again, please. Invalid input.' break else: if dave: print('\nI know you\'re distracted, but please use proper input.') else: print('Have a sip of carefree coffee and try again.') except ValueError: choice = 0 if dave: print('\nI know you\'re distracted, but please use proper input.') else: print('Have a sip of carefree coffee and try again.') print '\nWhat do you do next?' if dave: print('\nLunch time. You still haven\'t heard from Dave. Time to go check on him.') else: ddisplay.print_from_file("resources/story/ch02/ch02_worked.txt") raw_input('\n(Press enter key to continue)') return dave
def main(): #initialize pygame module and set window pygame.init() #DISPLAY WINDOW SIZE. CHANGE TO SUIT YOUR SCREEN IF NECESSARY width, height = 1800,900 pygame.display.set_icon(pygame.image.load('res/gameicon.jpg')) screen = pygame.display.set_mode((width,height), HWSURFACE|OPENGL|DOUBLEBUF) pygame.display.set_caption("Pylot") glViewport(0,0,width,height) glEnable(GL_DEPTH_TEST) default_view = np.identity(4) #boolean variables for camera view, lose screen, and pause FPV = True LOSE = False PAUSE = False KEYBOARD = False DATA = True #SIMULATION FRAMERATE #pygame limits framerate to this value. Increasing framerate improves accuracy of simulation (max limit = 60) but may cause some lag in graphics target_framerate = 60 #initialize graphics objects #loading screen is rendered and displayed while the rest of the objects are read and prepared glClearColor(0.,0.,0.,1.0) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) loading = graphics.Text(150) loading.draw(-0.2,-0.05,"Loading...",(0,255,0,1)) pygame.display.flip() #initialize game over screen gameover = graphics.Text(150) #initialize graphics aircraft graphics_aircraft = graphics.Mesh("res/Cessna.obj","shaders/aircraft.vs","shaders/aircraft.fs","res/cessna_texture.jpg",width,height) graphics_aircraft.set_orientation([0.,0.,0.,0.]) graphics_aircraft.set_position([0.,0.,-500.]) #initialize HUD HUD = graphics.HeadsUp(width, height) #initialize flight data overlay data = graphics.FlightData() #initialize field field = graphics.Mesh("res/field.obj","shaders/field.vs","shaders/field.fs","res/field_texture.jpg",width,height) field.set_position(np.array([0.,0.,0.])) #initialize camera object cam = graphics.Camera() a_obj = aircraft.Aircraft() dt = simulation.load_file('11.24_input.json', a_obj) simulation.initialize(a_obj) #initialize other pygame elements if pygame.joystick.get_count()>0.: joy = pygame.joystick.Joystick(0) joy.init() else: KEYBOARD = True thr = 0. UP = False DOWN = False RIGHT = False LEFT = False WW = False SS = False AA = False DD = False #DEFLECTION LIMITS FOR CONTROL SURFACES d_ail = 15. d_ele = 15. d_rud = 15. #clock object for tracking frames and timestep clock = pygame.time.Clock() #ticks clock before starting game loop clock.tick_busy_loop() #game loop while True: #event loop checks for game inputs such as joystick and keyboard commands for event in pygame.event.get(): if event.type == QUIT: return if KEYBOARD == False: if event.type == pygame.JOYBUTTONDOWN: if event.button ==2: FPV = not FPV cam.pos_storage.clear() cam.up_storage.clear() cam.target_storage.clear() else: if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: UP = True if event.key == pygame.K_DOWN: DOWN = True if event.key == pygame.K_LEFT: LEFT = True if event.key == pygame.K_RIGHT: RIGHT = True if event.key == pygame.K_w: WW = True if event.key == pygame.K_s: SS = True if event.key == pygame.K_a: AA = True if event.key == pygame.K_d: DD = True if event.key == pygame.K_SPACE: FPV = not FPV cam.pos_storage.clear() cam.up_storage.clear() cam.target_storage.clear() if event.type == pygame.KEYUP: if event.key == pygame.K_UP: UP = False if event.key == pygame.K_DOWN: DOWN = False if event.key == pygame.K_LEFT: LEFT = False if event.key == pygame.K_RIGHT: RIGHT = False if event.key == pygame.K_w: WW = False if event.key == pygame.K_s: SS = False if event.key == pygame.K_a: AA = False if event.key == pygame.K_d: DD = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_i: DATA = not DATA #pause simulation if event.key == pygame.K_p: PAUSE = not PAUSE #quit game if event.key == pygame.K_q: return #maintains framerate even if sim is paused if PAUSE == True: clock.tick(target_framerate) #if game is not paused, runs sim if PAUSE == False: #set default background color for sky glClearColor(0.65,1.0,1.0,1.0) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) #timestep for simulation is based on framerate t= clock.tick(target_framerate)/1000. # if joystick is being used, gets joystick input and creates control_state dicitonary if KEYBOARD == False: control_state = { "aileron": (joy.get_axis(0)**3)*-d_ail, "elevator": (joy.get_axis(1)**3)*-d_ele, "rudder": (joy.get_axis(3)**3)*-d_rud, "throttle": (-joy.get_axis(2)+1.)*0.5, "flaps": 0. } # if joystick is not being used, gets keyboard input and creates control_state dictionary else: if UP == True and DOWN == False: ele = 1. elif UP == False and DOWN == True: ele = -1. else: ele = 0. if LEFT == True and RIGHT == False: ail = 1. elif LEFT == False and RIGHT == True: ail = -1. else: ail = 0. if AA == True and DD == False: rud = 1. elif AA == False and DD == True: rud = -1. else: rud = 0. if WW == True and SS == False and thr<=1.0: thr += 0.05 elif WW == False and SS == True and thr>=0.0: thr -= 0.05 control_state = { "aileron": ail*d_ail, "elevator": ele*d_ele, "rudder": rud*d_rud, "throttle": thr, "flaps": 0. } #SIMULATION CALCULATIONS GO BELOW HERE FOR EACH TIME STEP #IT IS RECOMMENDED THAT YOU MAKE AN OBJECT FOR THE SIMULATION AIRCRAFT AND CREATE A FUNCTION IN SAID OBJECT TO CALCULATE THE NEXT TIME STEP. #THIS FUNCTION CAN THEN BE CALLED HERE simulation.run_sim(a_obj, dt) #INPUT POSITION, ORIENTATION, AND VELOCITY OF AIRCRAFT INTO THIS DICTIONARY WHICH WILL THEN UPDATE THE GRAPHICS aircraft_condition = { "Position":a_obj.state_vars[6:9],#input position of form [x,y,z] "Orientation":a_obj.state_vars[-4:],#input orientation in quaternion form [e0,ex,ey,ez] "Velocity":a_obj.state_vars[:4] #input Velocity of form [u,v,w] } flight_data = { "Graphics Time Step": t,#sec "Physics Time Step": dt,#sec "Airspeed": a_obj.V_now,#feet/sec "AoA":a_obj.alpha_now ,#deg "Sideslip": a_obj.beta_now ,#deg "Altitude":-a_obj.state_vars[8] ,#feet "Latitude":a_obj.state_vars[6] ,#deg "Longitude":a_obj.state_vars[7] ,#deg "Time":0. ,#sec "Bank":a_obj.bank ,#deg "Elevation":a_obj.elevation ,#deg "Heading":a_obj.heading ,#deg "Gnd Speed":a_obj.V_now ,#feet/sec "Gnd Track":0. ,#deg "Climb":a_obj.climb, #feet/min # "Throttle":control_state["throttle"]*100 ,#% # "Elevator":control_state["elevator"] ,#deg # "Ailerons":control_state["aileron"] ,#deg # "Rudder":control_state["rudder"] ,#deg # "Flaps":control_state["flaps"] ,#deg "Throttle":a_obj.tau_o ,#% "Elevator":a_obj.de_o ,#deg "Ailerons":a_obj.da_o ,#deg "Rudder":a_obj.dr_o ,#deg "Flaps":0.,#deg "Axial G-Force":0. ,#g's "Side G-Force":0. ,#g's "Normal G-Force":0. ,#g's "Roll Rate": a_obj.p_o ,#deg/s "Pitch Rate":a_obj.q_o ,#deg/s "Yaw Rate":a_obj.r_o #deg/s } #apply position and orientation to graphics graphics_aircraft.set_orientation(graphics.swap_quat(aircraft_condition["Orientation"])) graphics_aircraft.set_position(aircraft_condition["Position"]) #test game over conditions if graphics_aircraft.position[2]>0.: LOSE = True #if you get a game over, display lose screen if LOSE == True: glClearColor(0,0,0,1.0) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) gameover.draw(-0.2,-0.05,"Game Over",(0,255,0,1)) PAUSE = True #otherwise, render graphics #Third person view elif FPV == False: #get view matrix and render scene view = cam.third_view(graphics_aircraft) graphics_aircraft.set_view(view) field.set_view(view) graphics_aircraft.render() field.render() if DATA == True: data.render(flight_data) #cockpit view elif FPV == True: view = cam.cockpit_view(graphics_aircraft) field.set_view(view) field.render() if DATA == True: data.render(flight_data) HUD.render(aircraft_condition,view) #update screen display pygame.display.flip()
parameter_dictionaries = [] dirs = [] for density in density_of_sources: dic['density_of_stars'] = density dic['data_dir'] = '{0:.3f}'.format(density) dirs.append('{0:.3f}'.format(density)) parameter_dictionaries.append(dic.copy()) if multi_proc: os.nice(19) from multiprocessing import Pool p = Pool(processes=multi_proc) p.map(simulation.run_sim, parameter_dictionaries) else: for params in parameter_dictionaries: simulation.run_sim(params) # Read timings from individual directories density = np.zeros(len(dirs)) time_measurement = np.zeros(len(dirs)) time_self_cal = np.zeros(len(dirs)) for indx in range(len(dirs)): f = open(dirs[indx] + '/timings.txt', 'r') density[indx] = float(dirs[indx]) time_measurement[indx] = float( f.readline().strip('Measurement Catalog (s): ')) time_self_cal[indx] = float(f.readline().strip('Self-Calibration (s): ')) fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0.15, 0.15, 0.8, 0.8])
def simulate_fitness(traits, trial, gen, difficulty_level): candidate = sim.run_sim(traits, trial, gen, difficulty_level) return candidate[0]
def flight_simulator(filename, t0): a_obj = aircraft.Aircraft() dt, t_lim = simulation.load_file(filename, a_obj) simulation.initialize(a_obj) simulation.run_sim(a_obj, t0, dt, t_lim)