def start_simulation(self, widget): N = [] t_zero = time.time() for i in range(0, len(self.Nodes)): N.append([[0, 0], 0]) M = Map(self.Nodes, self.Connectors) S = Simulation(10, 2, self.Nodes, self.Connectors) print "Nodes: " + str(self.Nodes) print "Connectors: " + str(self.Connectors) self.Vehicles = utils.generate_vehicles(self.Connectors) print "Vehicles: " + str(self.Vehicles) M.disp_map() while True: time.sleep(0.05) [N, self.Vehicles] = S.simulate_vehicles(self.Vehicles, N) M.disp_vehicles(self.Vehicles, N) #M.disp_infections(self.Vehicles, N) for event in pygame.event.get(): if event.type == pygame.QUIT: M.close_window() #DB.save(x) self.info.set_text("Runtime: " + str(time.time() - t_zero) + "s") print "Runtime: " + str(time.time() - t_zero) + "s" return 0
def __init__(self): if os.path.exists('Larticles_Options.pickle'): file = open('Larticles_Options.pickle', 'rb') self.options_file = pickle.load(file) file.close() else: self.options = Options() self.size = self.options.size self.suns = self.options.suns self.simulation = None self.simulation_button_pos = [200, 200, 300, 100] self.simulation_button_tekst = 'Simulation' self.simulation_button_kleur = [255, 0, 0] self.simulation_tekst_kleur = [0, 0, 0] self.options = Options() self.options_button_pos = [700, 200, 300, 100] self.options_button_tekst = 'Options' self.options_button_kleur = [100, 255, 100] self.options_tekst_kleur = [0, 0, 0] self.helper = Helper() self.helper_button_pos = [1200, 200, 300, 100] self.helper_button_tekst = 'Help' self.helper_button_kleur = [100, 100, 255] self.helper_tekst_kleur = [0, 0, 0] if testing: self.simulation = Simulation() self.simulation.Simulation_run()
def __init__(self, n_arms, n_runs, n_timesteps, models, problem=None, seed=100): self.n_arms = n_arms self.n_runs = n_runs # model is passed in the list format whose element is an object of a bandit model. self.models = models self.n_models = len(self.models) # problem self.problem = NormalBanditProblem( n_arms) if problem is None else problem # object for simulation of each run self.simulation = Simulation(self.models, self.n_arms, self.problem, n_timesteps) # storage for performance metrics self.opt_arm_ratio = np.zeros((self.n_models, n_timesteps)) self.regret = np.zeros((self.n_models, n_timesteps)) self.cumulative_reward = np.zeros((self.n_models, n_timesteps)) np.random.seed(seed)
def build_track(self): file = Parse('bach_846.mid') #file = Parse('WTC_Part1/Fugue7.mid') tpm = file.parse() simulate = Simulation(tpm, self) simulate.next_state(simulate.get_init_note(), self.length)
def main(): global command command = np.array((0.0, 0.0)) GUI.init(window_size) sim = Simulation() frames = 0 commands = [] while True: t = clock.tick(FPS) / 1000.0 if not handleEvent(pygame.event.poll()): break sim.run_step(t, command) if sim.state == State.landed: print(sim.rocket_velocity) print("Landed!") break elif sim.state == State.crashed: print(sim.rocket_velocity) print("Crashed.") break elif sim.state == State.outOfBounds: print("Outside of bounds.") break GUI.update(sim.rocket_pos, rocket_size, ground_pos, ground_size) frames += 1 commands.append(command.copy()) print("Frames: " + str(frames))
def run_tests(learning_rate, time_step, no_iteration): #no_iteration = int(np.load("results/counter.npy")) #np.save("counter.npy", np.array([1 + no_iteration])) print("Iteration began: ", no_iteration) meta = open("results/iteration_metadata.txt", "a+") meta.write( str(no_iteration) + " " + str(learning_rate) + " " + str(time_step) + "\n") meta.close() p = generate_particles(particles, dimensions) nqs = NeuralQuantumState(initial_sigma, nx, nh, dimensions) h = Hamiltonian(nqs) sys = System(p, h) sim = Simulation(sys) nqs_opt = sim.stochastic_gradient_descent(tolerance, learning_rate, mc_iterations, max_iterations, sampling, update_radius, time_step, burn_in_percentage, no_iteration) #end_time = time.time() #print("Time spent: ", end_time - start_time, " seconds.") return 5 * learning_rate
def getTimeseries(ax, simulation: Simulation, muuttuja, conversionFactor=1.0): if isinstance(simulation, list): for simulationInstance in simulation: ax = Plot.getTimeseries(ax, simulationInstance, muuttuja, conversionFactor) return ax ts = simulation.getTSDataset() try: dataset = ts[muuttuja] except KeyError: print("KeyError") return None # conversion dataset = dataset * conversionFactor dataset.plot(ax=ax, color=simulation.getColor(), label=simulation.getLabel(), linewidth=simulation.getLineWidth()) return ax
def __init__(self, figurefolder, datafolder, xstart=28., xend=32., draftLimit=0.1): self.figurefolder = pathlib.Path(figurefolder) self.figurefolder.mkdir(parents=True, exist_ok=True) self.datafolder = pathlib.Path(datafolder) self.xstart = xstart self.xend = xend self.draftLimit = draftLimit self.simulation = Simulation(self.datafolder, "Prognostic", Colorful.getDistinctColorList("red")) print("Folders", self.figurefolder, self.datafolder) self.simulation.setAUXDataset( "AeroB", "case_isdac_LVL5_3D_iceD_inter_48h_S_Nabb.nc") self.simulation.setAUXDataset( "CloudB", "case_isdac_LVL5_3D_iceD_inter_48h_S_Ncbb.nc") self.simulation.setAUXDataset( "IceB", "case_isdac_LVL5_3D_iceD_inter_48h_S_Nibb.nc") self.simulation.setAUXDataset( "Updraft", "case_isdac_LVL5_3D_iceD_inter_48h_w.nc") self.simulation.setTimeCoordToHours() self.simulation.sliceByTimeAUXDataset(self.xstart, self.xend)
def optimize(self, dim=None): num_iteration = 0 random.seed() if not dim: dim = self.DIM vec = (random.randint(0, 10 * self.DIM), random.randint(0, 10 * self.DIM), random.randint(0, 10 * self.DIM)) best_vec = vec best_score = sys.maxint iterations_since_new_best = 0 while num_iteration < self.MAX_ITERATIONS and iterations_since_new_best < 50: num_iteration += 1 sim = Simulation(self.DIM, self.TIME, vec[0], vec[1], vec[2]) cost_v = self.cost(vec) num_sick = sim.run() score = cost_v * num_sick # print "Iteration #: %s, Score: %s, Cost: %s. Num sick: %s, Masks: %s, Doses: %s, Vaccines: %s" % (num_iteration, score, cost_v, num_sick, vec[0], vec[1], vec[2]) if score < best_score: best_vec = vec best_score = score iterations_since_new_best = 0 else: iterations_since_new_best += 1 vec = self.getNeighbor(best_vec) num_iteration += 1 print best_vec print best_score return (best_vec, best_score)
def run_simulation(): get_dir() sim = Simulation() time, count = sim.run_simulation() if par.plot_grid: generate_gif() return time, count
def main( self ): configurationFile='MarketFeedSimulator.cfg' try: fp = open( configurationFile, 'r' ) log( "Processing configuration file %s" % ( configurationFile ) ) except: log( "Failed to open configuration file %s" % ( configurationFile ) ) log( "Aborting!" ) exit(1) cfg = Configuration() cfg.processConfigurationFile( fp ) log( "Starting feed simulation", LogLevel.INFO ) securityUniverse = getSecurityUniverse( securityMasterFilePath = cfg.universe['universe_file'] ) log( "Loaded Universe of %d securities" % ( len( securityUniverse ) ), LogLevel.INFO) self.message_publisher = messagePublisher( cfg ) self.simulation = Simulation( securityUniverse, self.message_publisher ) signal.signal( signal.SIGINT, self.onExit ) log( "Simulation starting", LogLevel.INFO ) self.simulation.start() self.rpc_consumer = RpcConsumer( cfg, stop_callback=self.onExit, change_freq_callback=self.simulation.changeFrequency ); self.rpc_consumer.consume()
def main(): print("Choose a .wav file to simulate...") orden = 10 fs, x = wav.read(easygui.fileopenbox()) showEstimation = easygui.ynbox( 'Do you want to see the S filter estimation?', 'S Filter Estimator', ('Yes', 'No')) x = x / 2.0**15 # Normalizo la entrada porque esta como bytes enteros if x[0].shape != (): # Si es estereo solo agarro 1 canal x = x.transpose()[0] # x = np.array([0.5*np.sin(2*3.142*i * 400/44100.0) for i in range(661500)]) # Si le quiero meter una senoidal perfecta. print("Simulation Started") sim = Simulation(x, fs, 10) sim.approximateS(1, showEstimation=showEstimation) en, test = sim.simulate() wav.write("out.wav", fs, np.array(en * 2.0**15, dtype='int16')) # Ploteo la salida plotResults = easygui.ynbox('Do you want to plot the ANC Results?', 'Results', ('Yes', 'No')) if plotResults: graphics = PlotTool() showTestProbe = easygui.ynbox('Do you want to show the Test Probe?', 'Results', ('Yes', 'No')) if showTestProbe: graphics.plot(x, en, fs, test=test) else: graphics.plot(x, en, fs, test=None) print("Output from the ANC out.wav has been created.") input("Press Enter to exit...")
def opt_wrapper(params): """ optimizing for periods """ # assign parameters periods_bol = int(params[0]) # space from optimizer returns floats periods_adx = int(params[1]) periods_rsi = int(params[2]) adx_value = int(params[3]) ###### Define Simulations ###### data = Data(start_date="20-03-01") # historical data interfal: hours df = data.load() strategy = Strategy(df=df, periods_bol=periods_bol, periods_adx=periods_adx, periods_rsi=periods_rsi, adx_value=adx_value) account = Account(balance={"euro": 1000, "btc": 0}, av_balance=0.8) sim = Sim(strategy=strategy, account=account, stake_amount=50, stop_loss=0.02) sim_result = sim.start() # negate as optimization looks for a minimum sim_result = -sim_result["account"].balance["euro"] return sim_result
def __init__(self, config): wx.Frame.__init__( self, None, title="Timetable Editor / Simulator v%s" % config.VERSION, size=(config.UI_WORKSPACE_WIDTH, config.UI_WORKSPACE_HEIGHT)) self.SetMinSize((1600, 900)) self.config = config self.width = self.GetSize()[0] self.height = self.GetSize()[1] # Set menu bar self.SetMenuBar(MenuBarWorkspace(self)) # Simulation Setup self.s = Simulation(config) # LoadSubjectInfo(self.s, config.FILE_SUBJECT_INFO) # LoadStudentSurvey(self.s, config.FILE_STUDENT_SURVEY) # LoadInstructorSurvey(self.s, config.FILE_INSTRUCTOR_SURVEY) # LoadClassroomInfo(self.s, config.FILE_CLASSROOM_INFO) if config.OPTION_LOADMODE: logging.info("Load mode") self.s.Load() else: logging.info("Execute Mode") # self.s.Execute() # Set Main Panel p = PanelWorkspace(self, config, self.s) self.Show()
def evaluateFitness(self): if not self.fitness: sim = Simulation() commands = self.getCommandList() sim.run_with_commands(commands) self.fitness = sim.evaluateFitness()
class SimulationTest: def __init__(self, file_name, timestep, num_iterations): self.simulation = Simulation(file_name, timestep, num_iterations) def run(self): self.simulation.run_simulation() pass
def start_work(self, x_value, digits_count, population_size, generations_number, elite_strategy_value, inversion_probability, crossing_probability, mutation_probability, selection_method_name, tournament_size, mutation_method_name, crossing_method_name, minimum, k_selection): file = open("result.txt", "w") elite_strategy_count = round(population_size * elite_strategy_value) variables_names = ['x', 'y'] chromosome_size = calculate_the_number_of_genes(x_value) + digits_count population = make_random_population(population_size, chromosome_size, variables_names) precisions = {"x": digits_count, "y": digits_count} if minimum: fitness_function = partial(ackley_function_minimum_fitness_funtion, precisions) else: fitness_function = partial(ackley_function_maximum_fitness_funtion, precisions) selection_strategy = self.create_strategy(self.selection_methods[selection_method_name]) selection_strategy["count"] = round(population_size - elite_strategy_count) selection_strategy["fitness_function"] = fitness_function selection_strategy["tournament_size"] = tournament_size selection_strategy.check_required_parameters() mutation_strategy = self.create_strategy(self.mutation_methods[mutation_method_name]) mutation_strategy["chromosomes"] = variables_names mutation_strategy["probability"] = mutation_probability mutation_strategy["min"] = -x_value mutation_strategy["max"] = x_value - 1 mutation_strategy["precision"] = digits_count mutation_strategy["fill"] = chromosome_size mutation_strategy.check_required_parameters() crossing_strategy = self.create_strategy(self.crossing_methods[crossing_method_name]) crossing_strategy["chromosomes"] = variables_names crossing_strategy["probability"] = crossing_probability crossing_strategy["k_selection_function"] = lambda: k_selection crossing_strategy["precisions"] = precisions crossing_strategy["fills"] = {"x": chromosome_size, "y": chromosome_size} crossing_strategy.check_required_parameters() inversion_strategy = Inversion() inversion_strategy["chromosomes"] = variables_names inversion_strategy["probability"] = inversion_probability inversion_strategy.check_required_parameters() elite_strategy = EliteStrategy() elite_strategy["count"] = elite_strategy_count elite_strategy["fitness_function"] = fitness_function elite_strategy["tournament_size"] = tournament_size elite_strategy.check_required_parameters() simulation = Simulation(population, generations_number, selection_strategy, crossing_strategy, mutation_strategy, fitness_function, elite_strategy, inversion_strategy, minimum) result_params, result_value, value_history = simulation.simulate() self.gui.show_result(result_params, result_value) PlotGenerator().generate(value_history, minimum) for epoch in value_history: file.write(str(epoch) + '\n') file.close()
def main(): sim = Simulation() sim.initialize() #sim.run(5000, False) #sim.plot_energy() sim.plot_movie()
def simulation(args): (strats, board_str, random_order) = args seed = random.randrange(sys.maxsize) random.seed(seed) #print("Seed: " + str(seed)) sim = Simulation(strats, board_str, random_order) turns, winners, points, roads, settlements, cities = sim.run() return (turns, winners, points, roads, settlements, cities)
def __init__(self): Simulation.__init__(self) # Used by the super save and load function. self.set_name("morph") self.debug = False self.plot_param['use_tex'] = True
def main(): args = parser.parse_args() population = args.population generations = args.generations mutation_rate = args.mutation_rate tests = args.tests seed = args.seed Simulation.run(population, generations, mutation_rate, tests, seed)
def setup(self): Simulation.setup(self) kitchen = Kitchen(self.home, "Kitchen") cubbyRoom = Room(self.home, "Cubby Room") diningRoom = Room(self.home, "Dining Room") den = Room(self.home, "Den") joshuaBedroom = Room(self.home, "Joshua's Room") calebBedroom = Room(self.home, "Caleb's Room") raychelBedroom = Room(self.home, "Raychel's Room") sarahBedroom = Room(self.home, "Sarah's Room") parentBedroom = Room(self.home, "Parent's Room") hallway1 = Room(self.home, "Hallway1") hallway2 = Room(self.home, "Hallway2") hallway3 = Room(self.home, "Hallway3") frontEntry = Room(self.home, "Front Entry") greyBathroom = Bathroom(self.home, "Grey Bathroom") greenBathroom = Bathroom(self.home, "Green Bathroom") playroom = Room(self.home, "Playroom") upstairsBathroom = Bathroom(self.home, "Upstairs Bathroom") parentBathroom = Bathroom(self.home, "Parent's Bathroom") laundryRoom = Room(self.home, "Laundry Room") kitchen.addConnection(cubbyRoom, 'N') kitchen.addConnection(diningRoom, 'N') den.addConnection(frontEntry, 'N') den.addConnection(cubbyRoom, 'N') den.addConnection(diningRoom, 'N') frontEntry.addConnection(playroom, 'N') frontEntry.addConnection(hallway1, 'N') hallway1.addConnection(greyBathroom, 'N') hallway1.addConnection(sarahBedroom, 'N') hallway1.addConnection(joshuaBedroom, 'N') hallway1.addConnection(hallway2, 'N') hallway2.addConnection(calebBedroom, 'N') hallway2.addConnection(greenBathroom, 'N') hallway2.addConnection(laundryRoom, 'N') hallway2.addConnection(hallway3, 'N') hallway3.addConnection(parentBedroom, 'N') parentBedroom.addConnection(parentBathroom, 'N') playroom.addConnection(raychelBedroom, 'N') playroom.addConnection(upstairsBathroom, 'N') joshua = Person(self.home, "Joshua", 22) emma = Person(self.home, "Emma", 20) beth = Person(self.home, "Beth", 47) raychel = Person(self.home, "Raychel", 19) sarah = Person(self.home, "Sarah", 14) caleb = Person(self.home, "Caleb", 21) david = Person(self.home, "David", 52) # ellen = Person(self.home, "Ellen", 18) # kaylee = Person(self.home, "Kaylee", 19) # gary = Person(self.home, "Grayson", 16) # anna = Person(self.home, "Anna", 16) # brock = Person(self.home, "Brock", 16) people = [joshua, emma, raychel, sarah, caleb, beth, david]
class SimulationController(): def __init__(self, n_arms, n_runs, n_timesteps, models, problem=None, seed=100): self.n_arms = n_arms self.n_runs = n_runs # model is passed in the list format whose element is an object of a bandit model. self.models = models self.n_models = len(self.models) # problem self.problem = NormalBanditProblem( n_arms) if problem is None else problem # object for simulation of each run self.simulation = Simulation(self.models, self.n_arms, self.problem, n_timesteps) # storage for performance metrics self.opt_arm_ratio = np.zeros((self.n_models, n_timesteps)) self.regret = np.zeros((self.n_models, n_timesteps)) self.cumulative_reward = np.zeros((self.n_models, n_timesteps)) np.random.seed(seed) def update_results(self, opt_arm_ratio_for_run, regret_for_run, cumulative_reward_for_run): self.opt_arm_ratio = self.opt_arm_ratio + opt_arm_ratio_for_run self.regret = self.regret + regret_for_run self.cumulative_reward = self.cumulative_reward + cumulative_reward_for_run def finalize_results(self): self.opt_arm_ratio = self.opt_arm_ratio / self.n_runs self.regret = self.regret / self.n_runs self.cumulative_reward = self.cumulative_reward / self.n_runs def reset(self): for _, model in self.models.items(): model.reset() self.simulation.reset() def run(self): for _ in np.arange(self.n_runs): self.problem.set_problem() opt_arm_ratio_for_run, regret_for_run, cumulative_reward_for_run = self.simulation.run( ) #print(opt_arm_ratio_for_run) self.update_results(opt_arm_ratio_for_run, regret_for_run, cumulative_reward_for_run) self.reset() #print(self.opt_arm_ratio) self.finalize_results() return self.opt_arm_ratio, self.regret, self.cumulative_reward
def run(self, masks=10, doses=10, vaccines=10): random.seed() sim = Simulation(self.DIM, self.TIME, masks, doses, vaccines) cost_v = self.cost((masks, doses, vaccines)) num_sick = sim.run() score = cost_v * num_sick # print "Score: %s, Cost: %s. Num sick: %s, Masks: %s, Doses: %s, Vaccines: %s" % (score, cost_v, num_sick, masks, doses, vaccines) # print "masks used: %s Doses used: %s Vaccines used: %s" % (sim.masks_used, sim.doses_used, sim.vaccines_used) return num_sick
def getTimeseries(ax, simulation: Simulation, muuttuja, conversionFactor=1.0): if isinstance(simulation, list): for simulationInstance in simulation: ax = Plot.getTimeseries(ax, simulationInstance, muuttuja, conversionFactor) return ax try: ts = simulation.getTSDataset() except FileNotFoundError: print("FileNotFoundError: Data from {0} not found in {1}. \ Continue with existing data".format(simulation.getLabel(), simulation.getFolder())) return ax try: dataset = ts[muuttuja] except KeyError: print("KeyError", simulation.getLabel(), simulation.getFolder()) return None # conversion dataset = dataset * conversionFactor dataset.plot(ax=ax, color=simulation.getColor(), label=simulation.getLabel(), linewidth=simulation.getLineWidth(), zorder=simulation.getZorder()) return ax
def createFile(self): self.s = Simulation() self.s.createRandomFile() self.delTree(self.tree) for i in range(len(self.s.fileList)): if self.s.fileList[i].isStore: tmp = [self.s.fileList[i].name, self.s.fileList[i].size, self.s.fileList[i].diskList] self.tree.insert("", i, values=tuple(tmp)) self.setStore(self.s.fileList[i].diskList, 'red')
def main(): """ Main method for running the entire program. Will prompt the user for input and then run the simulation. First checks tha valid XML files for both the user input and validation file are present. Each simulation tag is then checked against the validation file to make sure that it is properly formatted and all needed information is present. If any simulation tag contains errors the user is notified of these errors, and the simulation is not run. """ print ("Welcome to the 3D Photovoltaics Modeling.") done = False while not done: done = True filename = raw_input("Please enter the file path for your XML configuration file: ") try: valid = list(ET.parse("XML_Input/validation.xml")._root)[0] except Exception as e: done = False print("Validation file was not found. Validation file must be present inside of the XML_Input directory and should be named" "validation.xml.") try: inputted = ET.parse(filename) except Exception as e: done = False print("Error opening the input file: " + e.message) print("Please check your file path and make sure the XML is valid") simulation_tags = inputted.findall("simulation") simulation_dicts = [] passed_validation = True for i in range(len(simulation_tags)): errors = [] result = XML_Reader.map_validate_xml(simulation_tags[i], valid, errors) if len(errors) > 0: passed_validation = False print("On simulation tag number " + str(i+1) + " there were the following errors: \n") for error in errors: print(error) print("\n") else: simulation_dicts.append(result) if passed_validation: #run all of the simulations here setting_objects = [] for d in simulation_dicts: setting_objects.append((SimulationSettings(d), GraphSettings(d))) i = 1 for setting in setting_objects: s = Statistics() print("Running Simulation #" + str(i)) Simulation.run(setting[0], s) a = Analysis() a.generate_output(s, setting[0]) a.generate_graphs(setting[1]) i += 1
def main(): dateHandler = DateHandler() loader = Loader.loadPickle(fullFileName) #loader = Loader(dateHandler) #loader.loadCSV(startDate, numDays, fileToLoad) #loader.save(fullFileName) sim = Simulation(loader, dateHandler, adjStartDate, 20000) sim.run(loader)
def main(): #situation sit = reader.read(dirname(abspath(__file__))+'/../tools/data/bb.csv') #load data file for historical situation #requirement dam = BhumibolDam() #simple bhumibol dam requirement sim = Simulation(dam,sit,simple_alg) #make simulation with dam requirement, situation, and your chosen algorithm result = sim.run(True) #use sim.run() or sim.run(False) to abort when there is an error #it also returns the array or struct of bookkeeping result #try printing the result[0] to see what each element contain fig,ax = sim.plot(sit) ax.set_xlim(xmin=datetime.date(2009,01,01)) plt.show()
def run(self): for i in range(self.runs): S = Simulation(self.timesteps, self.pf_number, self.con_number, self.con_share, self.rest_number) S.iterate() an = Analyze(S) sorted_results = an.sort_pf_by_survival() for pf_n in range(self.pf_number): self.trans_distrib[pf_n, i] = sorted_results['trans'][pf_n] self.rest_distrib[pf_n, i] = sorted_results['rest'][pf_n] self.mult_distrib[pf_n, i] = sorted_results['mult'][pf_n] self.calc_av(self.trans_distrib, self.trans_av) self.calc_av(self.rest_distrib, self.rest_av)
def main(): logger = Logger() for n in range(1000, 100001, 1000): start_n_time = time.time() if n % 10000 == 0: print(f"{n / 1000}% done") n_data = [] for k in range(50): start_time = time.time() simulation = Simulation(n) simulation.run() n_data.append({"index": k, "answers": simulation.answers, "time": time.time() - start_time}) logger.log(n, json.dumps(n_data)) print(f"n={n} took {int(time.time() - start_n_time)} seconds")
def do_simulation(i): print 'Starting loop ' + str(i) sim = Simulation(hamiltonian,initial_states,mesolve_args) sim.regenerate_data_qubit_offsets() # Necessary for each run to have different displacement errors sim.args['cOpts']['tau']=taulist[i] sim.args['r']=[0, 0, d] sim.args['cOpts']['d']=d sim.run(taulist[i]/4,steps,1) #adjust for full circle! result_states = sim.last_run_all qsave(result_states, os.path.join(lind_args['folder'],"d-%d_state-%d"%(d*1e9,i))) #step_data = sim.last_run_quarter_cycle sim.reset_system_state() # return tuple of iteration and result, because jobs are started async = return whenever finished return (i, sim.last_run_all[-1])
def allocate_city(params): individuals = int(params["individuals"]) incubation = int(params["incubation"]) symptomatic = int(params["symptomatic"]) immunity = int(params["immunity"]) mortality = int(params["mortality"]) beacons = bool(params["beacons"]) scale_city = int(params["scale_city"]) max_rounds = int(params["max_rounds"]) simulation = Simulation(individuals, incubation, symptomatic, immunity, mortality, beacons, scale_city) save_simulation(simulation, max_rounds) simulation.start_simulation() return simulation.city
def getAllEvals2(best_solutions, nb_params, nb_evals, conv_thresh): """ Get all evaluations but with lists and not Solution objects """ start_time = time.time() e = {"all_evals": []} simulation = Simulation(nb_params, 0, None, conv_thresh) # id 0 so that argos seeds are random for i in range(len(best_solutions)): all_evaluations, nb_steps = simulation.evaluateMany(best_solutions[i][0], nb_evals) e[i] = (best_solutions[i][1], all_evaluations) # tuple e["all_evals"] += all_evaluations Utils.displayTiming(start_time) return e
def getAllEvals(best_solutions, nb_params, nb_evals, conv_thresh): """ Get all evaluations of 10 PSO runs with Solution objects e = {0: (sol1_eval, evaluations), 1 : (sol2_eval, evaluations), .. "tot": [all_evals]} """ start_time = time.time() e = {"all_evals": []} simulation = Simulation(nb_params, 0, None, conv_thresh) # id 0 so that argos seeds are random for i in range(len(best_solutions)): all_evaluations, nb_steps = simulation.evaluateMany(best_solutions[i].getValues(), nb_evals) e[i] = (best_solutions[i].getEval(), all_evaluations) # tuple e["all_evals"] += all_evaluations Utils.displayTiming(start_time) return e
def do_simulation(i): print 'Starting loop ' + str(i) if lind_args.get('specify_errors'): initial_states = calculate_initial_states_from_bitflips(bitflips[i]) else: initial_states = calculate_initial_states_from_bitflips(bitflips) sim = Simulation(hamiltonian,initial_states,mesolve_args) sim.loop = i sim.set_data_qubit_offsets(displacements) sim.choose_twirl(lind_args.get('twirl')) sim.run(time,steps) #adjust for full circle! result_states = sim.last_run_all qsave(result_states, os.path.join(lind_args.get('folder'),lind_args.get('subfolder'),'data','run'+str(i+1))) #step_data = sim.last_run_quarter_cycle sim.reset_system_state() # return tuple of iteration and result, because jobs are started async = return whenever finished return (i, sim.last_run_all[-1], sim.twirl)
def random_landmarks(h, w, dur, dt, N, csv_path): # Keep all robots and landmarks inside of a 10% barrier from the edges # of the environment min_x, max_x = int(w * 0.1), int(w - w * 0.1) min_y, max_y = int(h * 0.1), int(h - h * 0.1) # Keep a minimum Euclidean distance between the landmarks min_ed = int(min(w, h) * 0.1) # Now generate the landmarks and save them to a csv file new_landmarks = [] with open(csv_path, 'wb') as csv_file: landmark_writer = writer(csv_file, delimiter=',') while len(new_landmarks) < N: x, y = randint(min_x, max_x), randint(min_y, max_y) good = True # Make sure the landmarks are a minimum (Euclidean) distance apart for (x1, y1) in new_landmarks: if sqrt((x1-x)**2 + (y1-y)**2) < min_ed: good = False # Make sure we are still within the environment window if x < w and y < h and good: new_landmarks.append((x, y)) for (x, y) in new_landmarks: landmark_writer.writerow(['LANDMARK',x,y]) # Put a robot somewhere robot_placed = False while not robot_placed: x, y = randint(min_x, max_x), randint(min_y, max_y) good = True for (x1, y1) in new_landmarks: if sqrt((x1-x)**2 + (y1-y)**2) < min_ed: good = False if x < w and y < h and good: theta = uniform(0.0, 2.0*pi) landmark_writer.writerow(['ROBOT', x, y, theta, 15.0, 0.0]) robot_placed = True # Finally, run the simulation sim = Simulation(dur, dt, h, w, csv_path) sim.start()
def main(args): import signal import sys from time import sleep from Simulation import Simulation, SimulationParameters signal.signal(signal.SIGINT, signal_handler) if args.parameter_file: print("** Loading parameters from '%s'" % args.parameter_file) sim_params = SimulationParameters.load(args.parameter_file) else: print("** Creating parameters with random routes") sim_params = SimulationParameters() sim_params.grid_width = args.grid_size sim_params.grid_height = args.grid_size sim_params.n_agents = args.n_agents sim_params.steps_per_day = args.steps_per_day sim_params.max_days = args.max_days sim_params.memory_enabled = args.with_memory # never load this value from file simulation = Simulation(sim_params) print("** Storing parameters in '%s'" % PARAMS_OUT_FILE_NAME) simulation.get_parameters().save(PARAMS_OUT_FILE_NAME) # run simulation - would be nice if we could optionally wait for space between steps step_delay = 1.0 / args.fps while True: simulation_running = simulation.do_step() if not simulation_running: print("** Simulation finished") results_key = "sim_%i%s" % (args.sim_id, "T" if sim_params.memory_enabled else "F") store_results(results_key, simulation.get_jam_progression()) sys.exit(0) if args.fps > 0: sleep(step_delay)
def __init__(self): pygame.init() self.sprites = { 'projectile': pygame.image.load('projectile.bmp') } self.screen_width, self.screen_height = 900, 700 self.screen = pygame.display.set_mode((self.screen_width, self.screen_height)) self.simulation = Simulation(self) self.running = True self.sim_over = False self.graphics_on = True
class MainSimulation: def __init__(self): pygame.init() self.sprites = { 'projectile': pygame.image.load('projectile.bmp') } self.screen_width, self.screen_height = 900, 700 self.screen = pygame.display.set_mode((self.screen_width, self.screen_height)) self.simulation = Simulation(self) self.running = True self.sim_over = False self.graphics_on = True def updateLogic(self): self.simulation.updateLogic() def eval_fitness(self, genomes): self.sim_over = False self.simulation.eval_fitness(genomes) def display(self): if self.graphics_on: self.screen.fill(0) self.simulation.display() pygame.display.flip() def handleEvents(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_g and STEPBYSTEP: self.updateLogic() if event.key == pygame.K_y: self.graphics_on = not self.graphics_on def loop(self): # if not self.graphics_on: # print len(self.simulation.organisms) self.handleEvents() if not STEPBYSTEP: self.updateLogic() self.display()
l3_size = '2MB' l1d_assoc = '8' l1i_assoc = '8' l2_assoc = '16' l3_assoc = '16' cacheline_size = '64' properties = (l1d_size, l1i_size, l2_size, l3_size, l1d_assoc, l1i_assoc, l2_assoc, l3_assoc, cacheline_size) simulationsList = [] totalSim = 30 for i in range(totalSim): if i < (totalSim/3): simulation = Simulation("matrixMult", "ARM", properties) simulationsList.append((simulation, "mm", i)) elif i < 2*totalSim/3: simulation = Simulation("simon", "ARM", properties) simulationsList.append((simulation, "simon", i % (totalSim/3))) else: simulation = Simulation("binarySearch", "ARM", properties) simulationsList.append((simulation, "binarySearch", i % (totalSim/3))) for (simulation, program, counter) in simulationsList: filename = program + str(counter) filenameTrace = '/home/lpavel/gem5-stable/m5out/' + filename + 'Trace.txt' filenameOut = '/home/lpavel/gem5-stable/m5out/' + filename + 'Output.txt' simulation.run(filenameTrace) #after simulation runs, parse the output form stats.txt
def setUp(self): self.automaton = Automaton(ROWS, COLUMNS) self.simulation = Simulation(self.automaton, False)
def main(): s = Simulation("../properties/WorldMap2.props") s.run()
# Finally, run the simulation sim = Simulation(dur, dt, h, w, csv_path) sim.start() # Use a dialog box (filled with defaults) to get the parameters for the # simulation def get_simulation_parameters(): root = Tk() dlg = ParametersDialog(root, title="Simulation Parameters") root.destroy() if dlg.result(): h, w, dur, dt = dlg.result()[0], dlg.result()[1], dlg.result()[2], dlg.result()[3] new_landmarks, new_env_file, new_do_random = dlg.result()[4], dlg.result()[5] , dlg.result()[6] return h, w, dur, dt, new_landmarks, new_env_file, new_do_random return None if __name__ == "__main__": params = get_simulation_parameters() if params: (h, w, dur, dt, landmarks, env_file, do_random) = params if do_random: env_file = '../data/random_landmarks.env' random_landmarks(h, w, dur, dt, landmarks, env_file) else: h, w = 500, 500 sim = Simulation(dur, dt, h, w, env_file) sim.start()
from Cook import Cook from Restuarant import Restuarant from Simulation import Simulation sim = Simulation() sim.run()
#result = mesolve(Hz+Hi, psi0, tlist, linds, [])#, options=Odeoptions(nsteps=100000)) #result_states = result.states # use time dependent #tlist=linspace(0, tau/4., 40000) #one simulation is only a quarter of the turn! #result = mesolve(H, psi0, tlist, [], [])#, options=Odeoptions(nsteps=100000)) #result_states = result.states # ------- BEGIN SIMULATION CODE -------- hamiltonian = Hz+Hi initial_states = [(pi/2.0,0),(0,0),(0,0),(pi,0),(0,0)] # [(theta,phi),...] for all qubits mesolve_args = [] sim = Simulation(hamiltonian,initial_states,mesolve_args) #sim.lind.dephasing(1.0e3,0) # example of adding Lindblad operators (dephase probe) #sim.run(8*78e-6,12000) # total time, total steps, num of cycles (default 4) #result_states = sim.last_run_all #step_data = sim.last_run_quarter_cycle #sim.set_system_state(initial_states) # Set full system state to whatever you want """ Code-block for extracting states from the simulation runs and putting them in an array""" final_states = [] iterations = 12000 tau = 8*78.e-6 sim_no = 5 for i in range(0,2):
""" Prepare Hamiltonian """ ham=H_RWA(config) hamiltonian = ham.getHfunc() """ Prepare Bloch Sphere settings """ db=Bloch() colors = ["g"]#,"r","g","#CC6600"]#,"r","g","#CC6600"] db.point_color = "r" db.point_marker = ['o'] """ Set up simulation """ mesolve_args = ham.getArgs() steps = config_args['steps'] time = config_args['time'] no_of_runs = lind_args['runs'] sim = Simulation(hamiltonian,initial_states,mesolve_args) final_states = [] """Adding Lindblad operators""" if lind_args.get('dephasing'): sim.lind.dephasing(lind_args.get('dephasing_param')) if lind_args.get('excitation'): sim.lind.excitation(lind_args.get('excitation_param')) if lind_args.get('relaxation'): sim.lind.relaxation(lind_args.get('relaxation_param')) """ Set up and generate qubit displacements """ if lind_args.get('qubit_displacement_error'): disp_radius = float(lind_args.get('qubit_displacement_radius')) disp_halfheight = float(lind_args.get('qubit_displacement_halfheight'))
graphErgo.generateurErgo() bob_question10 = Internaute(graphErgo) bob_question10.goTo(0) start = time.time() #debut bob_question10.walk(1000,0.001) print "bob_question10 a mis : ", time.time()-start ," de ms " #print graphErgo.matrice pi_0 = np.zeros(graphErgo.taille) pi_0[3] = 1 simula = Simulation(graphErgo) start = time.time() simula.simul(1000,0.001,pi_0) print "simulation vecteur * matrice a mis : ", time.time()-start," de ms" start = time.time() graphErgo.convergePuissance(0.001) print "simulation puissance matrice a mis : ",time.time() - start, " de ms" """Generation d'un graphe ergodique avec generateurErgo()"""
""" This script is used to execute the cellular automaton Chile """ from Automaton import Automaton from Simulation import Simulation from Analyzer import Analyzer from Agent import Agent # TODO: USE A GUI TO CONFIG THESE PARAMETERS COLUMNS = 30 ROWS = 30 POPULATION = 100 ITERATIONS = 20 # executing the main method of the code automaton = Automaton(ROWS, COLUMNS) analyzer = Analyzer(automaton) automaton.createPopulation(POPULATION, Agent.randomRangeRadiumUnif(1, 5)) simulation = Simulation(automaton, True) simulation.start(ITERATIONS) rankings = analyzer.getRankingOfPopulation() print analyzer.getLinearRegressionData(False)
class TestFitness(unittest.TestCase): def setUp(self): self.automaton = Automaton(ROWS, COLUMNS) self.simulation = Simulation(self.automaton, False) def test_infiniteRadium(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.createPopulation(POPULATION, Agent.infiniteRadium()) self.simulation.start(ITERATIONS) self.assertTrue(self.automaton.convergence, "IT IS CONVERGENCE") array = self.automaton.getMatrixOfPopulation() # print repr(self.automaton) + " " + repr(array.max()) self.assertEqual(POPULATION, len(self.automaton.getAgents()), "ALL AGENTS") def test_withZeroRadium(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.createPopulation(POPULATION, Agent.constRadium(0)) self.simulation.start(3) self.assertTrue(self.automaton.convergence, "IT IS CONVERGENCE") def test_random(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.createPopulation(POPULATION, Agent.infiniteRadium(), Agent.randomFitness) self.simulation.start(ITERATIONS) self.assertFalse(self.automaton.convergence, " IT IS NOT CONVERGENCE") def test_circularRangeInf(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.enableCircularGrid() rr = [0, 1, 2, 3, 4, 5, 17, 18, 19] rc = [0, 1, 2, 3, 4, 5, 27, 28, 29] ranges = self.automaton.getRanges(1, 1, 4) ranges[0].sort() ranges[1].sort() self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1])) def test_circularRangeSup(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.enableCircularGrid() rr = [0, 1, 2, 14, 15, 16, 17, 18, 19] rc = [0, 1, 23, 24, 25, 26, 27, 28, 29] ranges = self.automaton.getRanges(18, 27, 4) ranges[0].sort() ranges[1].sort() self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1])) def test_circularRangeAndWithoutRandomInf(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.enableCircularGrid() self.automaton.disableRandomVisitingOfCells() rr = [17, 18, 19, 0, 1, 2, 3, 4, 5] rc = [27, 28, 29, 0, 1, 2, 3, 4, 5] ranges = self.automaton.getRanges(1, 1, 4) self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1])) def test_circularRangeAndWithoutRandomSup(self): self.automaton.reinit(ROWS, COLUMNS) self.automaton.enableCircularGrid() self.automaton.disableRandomVisitingOfCells() rr = [14, 15, 16, 17, 18, 19, 0, 1, 2] rc = [23, 24, 25, 26, 27, 28, 29, 0, 1] ranges = self.automaton.getRanges(18, 27, 4) self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1])) def test_rangeWithoutRandomInf(self): self.automaton.reinit(ROWS, COLUMNS) rr = [0, 1, 2, 3, 4, 5] rc = [0, 1, 2, 3, 4, 5] ranges = self.automaton.getRanges(1, 1, 4) ranges[0].sort() ranges[1].sort() self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1])) def test_rangeWithoutRandomSup(self): self.automaton.reinit(ROWS, COLUMNS) rr = [14, 15, 16, 17, 18, 19] rc = [23, 24, 25, 26, 27, 28, 29] ranges = self.automaton.getRanges(18, 27, 4) ranges[0].sort() ranges[1].sort() self.assertEquals(rr, ranges[0], "Not same ranges for rows:" + repr(ranges[0])) self.assertEquals(rc, ranges[1], "Not same ranges for columns:" + repr(ranges[1]))
a_prod = IM1.add_edge('a','a','const_prod',params=[5.0]) # 'a' is produced at a constant rate IM1.add_edge('a','b','hill_activ',params=[5.0,1.0,2]) # 'a' activates 'b' IM1.add_edge('b','c','hill_activ',params=[6.0,1.0,8]) # 'b' activates 'c' (with sharper cutoff) IM1.add_edge('c',a_prod,'hill_inactiv',is_mod=True,mod_type='mult',params=[1.0,1.0,0.3,8]) # IM2 is a network with only a single species IM2 = InternalModel() IM2.add_node('a','linear',[1.0]) # we have 3 cells cell1 = Cell([0.0]) cell2 = Cell([1.0]) cell3 = Cell([2.0]) sim = Simulation() # add the cells and internal models to simulation cell1_id = sim.add_cell(cell1) cell2_id = sim.add_cell(cell2) cell3_id = sim.add_cell(cell3) im1_id = sim.add_internal_model(IM1) im2_id = sim.add_internal_model(IM2) sim.set_internal_model([cell1_id,cell2_id],im1_id) # first two cells have IM1 sim.set_internal_model([cell3_id],im2_id) # last cell as IM2 connections = np.array([[False,False,False],[False,True,True],[False,True,True]]) sim.add_interaction('a','a','diffusion',connections,params=[1.0]) # cell1 and cell2 start with the same initial conditions
datawriter.writerow(popStatVals) for i in simLog: runVals = i.getRunVals() newRow=[] newRow.append(startNumber) for j in runVals: newRow.append(j) datawriter.writerow(newRow) startNumber += 1 # -------------------------------------------------------- # main code body # create a new simulation, run it, and create all necessary output files for each simulation run for i in range(startNumber, numSims+startNumber): newSim = Simulation(i) newSim.preSimSetup() simLog.append(newSim.runSim()) newExport = Export(newSim) newExport.writeTimeLog(i) newExport.writeFinalPopulation(i) print('Finished Simulation ' + str(i)) #write the summary file for all simulation runs writeSimLog(simLog, startNumber)
from Simulation import InternalModel,Cell,Simulation import numpy as np import matplotlib.pyplot as plt IM1 = InternalModel() IM1.add_node('a') IM2 = InternalModel() IM2.add_node('a','linear',[1.0]) # a_prod = IM.add_edge('a','a','const_prod',params=[1.0]) cell1 = Cell([0.0]) cell2 = Cell([1.0]) cell3 = Cell([2.0]) sim = Simulation() cell1_id = sim.add_cell(cell1) cell2_id = sim.add_cell(cell2) cell3_id = sim.add_cell(cell3) IM1_id = sim.add_internal_model(IM1) IM2_id = sim.add_internal_model(IM2) connections = np.array([[False,False,False],[True,True,True],[False,True,True]]) sim.set_internal_model([cell1_id],IM1_id) sim.set_internal_model([cell2_id,cell3_id],IM2_id) a_diff = sim.add_interaction('a','a','diffusion',connections,params=[1.0]) def lin(x,t): return np.maximum((-x+t+np.sin(10.0*t))*(t < 6.0),1.0)
from Simulation import Simulation import csv try: # with open('output_data.csv', 'a+') as f: # fieldnames = ['M', 'N', 'B', 'K', 'e', 'Frame transmission', 'Upper bound Ft', 'Lower Bound Ft', 'Throughput', 'Upper Bound Tp', 'Lower Bound Tp'] # writer = csv.DictWriter(f, fieldnames = fieldnames) # writer.writeheader() for i in range(100): Test = Simulation() Test.run() input() except EOFError: pass
hamiltonian = ham.getHfunc() """ Prepare Bloch Sphere settings """ def prepare_bloch(): db=Bloch() colors = ["g"]#,"r","g","#CC6600"]#,"r","g","#CC6600"] db.point_color = "r" db.point_marker = ['o'] return db """ Set up simulation """ mesolve_args = ham.getArgs() steps = config_args['steps'] time = config_args['time'] no_of_runs = lind_args['runs'] sim = Simulation(hamiltonian,initial_states,mesolve_args) final_states = [] """Adding Lindblad operators""" if lind_args.get('dephasing'): sim.lind.dephasing(lind_args.get('dephasing_param')) if lind_args.get('excitation'): sim.lind.excitation(lind_args.get('excitation_param')) if lind_args.get('relaxation'): sim.lind.relaxation(lind_args.get('relaxation_param')) """ Set up and generate qubit displacements """ displacements = lind_args.get('displacement') displacements = [[float(x) for x in y] for y in displacements] # conversion from str to float sim.set_data_qubit_offsets(displacements)
''' CS97 Final Project Jess Jowdy and Isaac Dulin Does very little on its own. Simply creates an instance of the simulation class and then runs it. All of the actual work is done by the underlying classes. ''' from Simulation import Simulation if __name__ == '__main__': #Run the main code simulation = Simulation() simulation.runSimulation()