def main(argv=None): params = parse_args(argv) if params.agents < 1: raise Exception("Model requires at least two agents, got {} instead." .format(params.agents)) else: simulate(**params.__dict__)
def start(): if tamaño.get_value().isdigit() and iteraciones.get_value().isdigit(): tam = int(tamaño.get_value()) it = int(iteraciones.get_value()) if tam > 0 and it > 0: if tam > int(0.65 * (preferredSize // 2)): thorpy.launch_blocking_alert( title="¡Tamaño no soportado!", text= "El tamaño actual generaría una grilla con celdas de tamaño cero.", parent=background) tamaño.set_value("") else: simulation.simulate(tam, it, preferredSize) else: thorpy.launch_blocking_alert(title="¡Tamaño no soportado!", text="El tamaño no es válido.", parent=background) else: thorpy.launch_blocking_alert( title="¡Valores incorrectos!", text="Los valores introducidos no son válidos.", parent=background) tamaño.set_value("") iteraciones.set_value("")
def simulation_contact_tracing(n, p, times): interventions = [] mapping = { 'S': 'QS', 'E': 'QE', 'I1': 'Q1', 'I2': 'Q2', 'I3': 'Q3', 'R': 'R', 'D': 'D', 'Q1': 'Q1', 'Q2': 'Q2', 'Q3': 'Q3', 'QS': 'QS', 'QE': 'QE' } for time in times: interventions.append( ContactTracingIntervention(["I1", "I2", "I3"], mapping, p, time,) ) LG = setup_LG(n) M = QuorontracingModel(0, 0, 0) c_observer = CountObserver(quolor_palette.keys()) observers = [c_observer] M.init_states(LG, 5) simulate(LG, M, interventions, 50, observers) # scale x -axis return c_observer.data
def test_convergence_orders(): # Do not output the plots at the end of a simulation parameters.CONST_OUTPUT_PLOT = False for p in CONST_CONVERGENCE_TEST_P_VALUES: for ml in CONST_CONVERGENCE_TEST_ML_VALUES: # Modify the values in parameters.py parameters.CONST_ML = ml parameters.CONST_P = p # Perform the specified type of refinement if REFINEMENT_TYPE == "PATCHES": parameters.CONST_NUM_PATCH = parameters.CONST_NUM_PATCH_ML0 * ( 2**(parameters.CONST_ML)) # Update the number of patches parameters.CONST_NUM_BASIS = 12 elif REFINEMENT_TYPE == "KNOT": parameters.CONST_NUM_PATCH = 2 parameters.CONST_NUM_BASIS = parameters.CONST_NUM_BASIS_ML0 * ( 2**(parameters.CONST_ML) ) # Update the number of basis functions else: raise ValueError("Unkown REFINEMENT_TYPE") # Run the simulation simulation.simulate()
def run_strats(folder, topology, red_mult, black_mult, strat_list, iterations, runs): for strat in strat_list: print(str(strat)) start = time.time() # prefix = str(strat['threshold']) + '_' + str(strat['portion']) prefix = '' if strat.get('threshold') is not None: prefix = str(strat['threshold']) + '_' + str(strat['portion']) if prefix: infection_csv = folder + topology + prefix + strat[ 'red_strat'] + strat['black_strat'] + 'infection.csv' simulate(folder, topology, red_mult, black_mult, strat, iterations, runs, prefix=prefix) elapsed_time = time.time() - start print(elapsed_time) print() log_file = folder + 'log.txt' with open(log_file, 'a') as f: f.write(str(strat) + '\n') f.write(str(elapsed_time) + '\n') f.write('\n')
def robustness_delta(init_parameters, velocity, model, control, timespan,goals): phi, delta, d_phi, d_delta = init_parameters init_pkg = {'phi': phi, 'delta': delta, 'd_phi': d_phi, 'd_delta': d_delta} results = simulate(model, init_parameters, timespan, velocity, control, None,goal=goals) if not settles(results['t'], results['delta'], goals[1]): return 0 ################################continue here start = # find the max lowbd = start upbd = start + 30 max_var = (lowbd + upbd) / 2 while (abs(upbd) - abs(lowbd)) > 1e-2: init_parameters = max_var, init_pkg['delta'], init_pkg['d_phi'], init_pkg['d_delta'] results = simulate(model, init_parameters, timespan, velocity, control, None) if settles(results['t'], results['phi'], 0): lowbd = max_var else: upbd = max_var - 1 max_var = (lowbd + upbd) / 2 # find the min upbd = start lowbd = start - 30 min_var = (lowbd + upbd) / 2 while (abs(lowbd) - abs(upbd)) > 1e-2: init_parameters = min_var, init_pkg['delta'], init_pkg['d_phi'], init_pkg['d_delta'] results = simulate(model, init_parameters, timespan, velocity, control, None) if settles(results['t'], results['phi'], 0): upbd = min_var else: lowbd = min_var min_var = (lowbd + upbd) / 2 return max_var - min_var
def main(): params = parameters.Parameters() params.read(sys.argv[1:]) sim = False for task in params.task: if task == "app": dash_ui.launcher.launch_app(params) elif task == "help": if (len(sys.argv) > 2): params.help(sys.argv[2]) else: params.help() elif task == "track": tracking.track(params) elif task == "simulate": simulation.simulate(params) sim = True elif task == "postprocess": postprocessing.postprocess(params, simulated=sim) elif task == "view": visualisation.render(params) elif task == "compare": trajectories.compare_trajectories(params) else: sys.exit(f"ERROR: Task {task} is not yet implemented. Aborting...")
def main(): """ -------------initialbetingelser for simulasjonen -------------------""" #antall sekunder vi går mellom hvert steg deltat = args.deltat #feilmargin for vinkelen til planeten err = .2 #antall grader #random seed for random generatoren seed(42) #planeten/månen vi ønsker å observere rundetiden til planet = "" #systemet vi skal animere system = solar_system(planet) #planeten vi setter i sentrum av solsystemet centre = "" #vil vi se når planeten går rundt sentrumet i sin abolsutte bane, #eller relativt til et annet legeme (sentrumet til planetens bane)? relative_orbit = False """ -------------initialbetingelser for grafikken ----------------------""" #skalar slik at ting får plass i turtle-grafikkfeltet scalar = 100 #antall turtle-enheter per astronomisk enhet #antall steg vi venter mellom å oppdatere konsollinfo og linjer bak planetene step = 100 #kjører simulasjonen simulate(planet, centre, system, relative_orbit, deltat, err, scalar, step)
def simulation_age_model(n, b_kids, g_kids, p_kids, b_normal, g_normal, p_normal, b_risk, g_risk, p_risk): LG = setup_LG(n) AM = AgeModel(b_kids, g_kids, p_kids, b_normal, g_normal, p_normal, b_risk, g_risk, p_risk) c_observer = CountObserver(kolor_palette.keys()) AM.init_states(LG, 5) simulate(LG, AM, set(), 50, [c_observer]) return c_observer.data
def simulation_max_class(n, class_size, degree, p): if degree is None and p is None: LG, CH = setup_CH(n, classsize=class_size) else: LG, CH = setup_CH(n, classsize=class_size, degree=degree, p=p) CH.init_states(LG, 5) c_observer = CountObserver(color_palette.keys()) simulate(LG, CH, set(), 50, [c_observer]) return c_observer.data
def simulate_flows(K, flows, conf_file): import simulation simulation.simulate([ '--test', 'clos', '--duration', '240', '--delay', '100us', '--json', conf_file, str(K) ])
def simulation_max_quarantine_rates(n, q1, q2, q3): LG = setup_LG(n) CH = CoronaQuarantineModel(q1, q2, q3) # Observer c_observer = CountObserver(qolor_palette.keys()) observers = [c_observer] # Simulation CH.init_states(LG, 5) simulate(LG, CH, set(), 50, observers) return c_observer.data
def simulation_age_max_class(n, class_size, degree, p): if degree is None and p is None: LG = setup_LG(n, classsize=class_size) else: LG = setup_LG(n, classsize=class_size, degree=degree, p=p) AM = AgeModel(B_KIDS, G_KIDS, P_KIDS, B_NORMAL, G_NORMAL, P_NORMAL, B_NORMAL, G_NORMAL, P_NORMAL) AM.init_states(LG, 5) c_observer = CountObserver(kolor_palette.keys()) simulate(LG, AM, set(), 50, [c_observer]) return c_observer.data
def ohl(capital, star_param, cdata, typ): max_dp = star_param['MAX'] start = star_param['START'] thr = star_param['THR'] var = star_param['VAR'] sl = star_param['SL'] t1 = star_param['T1'] t2 = star_param['T2'] st_id = star_param['ID'] scr = star_param['SC'] sims = {} scrips = {} data = {} c.pr( "I", "Initialiazing Strategy OHL Max DP -> " + str(max_dp) + " Staring Data Point -> " + str(start), 0) #Fetch Scrips if scr == "ALL": scrips = c.load_scrips() else: scrips[scr] = 1 #Fetch Data for scrip in scrips: if scr != "ALL": if len(cdata): data = cdata else: data = c.fetch_scrip_data(scrip, start, 0) else: data = c.fetch_scrip_data(scrip, start, 0) spl_data = c.split_data(data, 36000) for ctr in spl_data: rddata = collections.OrderedDict(sorted(spl_data[ctr].items())) iddata = c.intrafy(rddata) sim_key, sim_data = ohl_process(iddata, thr, var, scrip, capital, max_dp, sl, t1, t2, st_id) if sim_key: sims[sim_key + "_" + scrip] = sim_data #Call Simulations if len(sims): rans = randomize(spl_data, sims, start, "09:31:00", "15:10:00", "OHL", capital, sl, t1, t2, st_id) c.pr("I", str(len(sims)) + " Actual Simulations Will Be Performed", 1) c.pr("I", str(len(rans)) + " Random Simulations Will Be Performed", 1) if typ == "B": for key in sims: sim.simulate(sims[key]) for key in rans: sim.simulate(rans[key]) else: sim.init_sim(sims, rans, st_id) return
def simulation_max_time(n, t): LG, CH = setup_CH(n) # Interventions layernames_to_p = { "Households": 1, "Schools": 0, "Workplaces": 0.01, "R_Workplaces": 0, "Social": 0, "parties": 0.00, "basic": 0.1} um_intervention1 = UpdateMultipleLayerIntervention(layernames_to_p, t) # Observer c_observer = CountObserver(color_palette.keys()) observers = [c_observer] # Simulation CH.init_states(LG, 5) simulate(LG, CH, {um_intervention1}, 50, observers) return c_observer.data
def run_simulation(conf): agent_1 = a.make_agent(pid.P1, conf) agent_2 = a.make_agent(pid.P2, conf) total_games = args.g for i in range(total_games): simulate(agent_1, agent_2) prefix = conf.get_prefix() p.plot_simulation_results(agent_1, agent_2, prefix) p.plot_scores(agent_1, agent_2, prefix) conf.log() print('Done')
def simulate(self, ventilator): simulate(ventilator) self.simulateVentilatorOneButton.grid_remove() self.simulateVentilatorTwoButton.grid_remove() self.simulateVentilatorTreeButton.grid_remove() self.showSimulateOptionsButton.grid(row=0, column=1) self.splitLabel1.grid(row=1, column=1) self.showGraphButton.grid(row=2, column=1) self.casesSummaryButton.grid(row=3, column=1) self.costsSummaryButton.grid(row=4, column=1)
def main(): parser = argparse.ArgumentParser( description= 'Calculate and render probabilities of matchups for the show "Are You The One?".' ) parser.add_argument( 'season', type=str, help='the name of a season available in the "seasons" folder, like "s1"' ) parser.add_argument('--profile', dest='profile', action='store_true', help='if provided, profiles the code') args = parser.parse_args() print(f'Reading season {args.season}') season_data = seasons.read_season(args.season) print(f'Preparing season') season = seasons.convert_season(season_data) print(f'Simulating season') with timer.start(args.profile) as t: output = simulation.simulate(season) print(f'Simulation completed in {t.elapsed} seconds') print(f'Plotting season') fig = plot.create_plot(season, output) fig.show()
def study_delay(): delay_means_ms = np.arange(0, 30e-3, 1e-3) final_errors = [] xs = [] for delay_mean_ms in delay_means_ms: delay_mean = delay_mean_ms delay_std = delay_mean / 10 print("Delay: ", delay_mean, delay_std) errors = [] for i in range(10): result = simulate( n=N, connect_closest=CONNECT_CLOSEST, delay_mean=delay_mean_ms, delay_sigma=delay_std, offset_sigma=OFFSET_SIGMA, skew_sigma=SKEW_SIGMA, simulation_length=60 * SIMULATION_MINUTES, ) # analyze.plot_single_run(result, f"../img/delay_mean{delay_mean_ms}.pdf") errors.append(result[-1].mean_error()) final_errors.append(min(errors)) xs.append(float(delay_mean)) analyze.plot_error(final_errors, xs, "../img/varying_delay.pdf") make_table(xs, final_errors)
def one_step_estimation(self, params): """ Takes as input the data moments. Starts with a guess for the parameters, calls the simulation.py class to simulate the resulting series from the policy, calls the compute_moments function to compute the moments of the simulated dataset, and then runs GMM. """ #alpha, beta, sigma = params[0], params[1], params[2] alpha, sigma = params[0], params[1] simulation = simulate(sigma, alpha, self.data) simulated_data = simulation.df actual_moments = self.data_moments simulated_moments = self.compute_moments(simulated_data) diff = simulated_moments - actual_moments d = np.size(diff) print(diff) weight = np.array([0.5, 0.5, 0.5, 0.5]) # np.array([0.1,0.1,0.8,0.5]) weight_matrix = np.eye(d) #np.diag(weight) score = diff.T @ weight_matrix @ diff return score
def run_simulation(): sht = xw.Book.caller().sheets[0] # User Inputs num_simulations = sht.range('E3').options(numbers=int).value time_horizon = sht.range('E4').value num_timesteps = sht.range('E5').options(numbers=int).value dt = time_horizon / num_timesteps # Length of time period vol = sht.range('E7').value mu = np.log(1 + sht.range('E6').value) # Drift starting_price = sht.range('E8').value perc_selection = [5, 50, 95] # Excel: clear output, write out initial values of percentiles/sample path and set chart source and x-axis values sht.range('O2').expand().clear_contents() sht.range('P2').value = [ starting_price, starting_price, starting_price, starting_price, perc_selection ] sht.charts['Chart 5'].set_source_data( sht.range((1, 15), (num_timesteps + 2, 19))) sht.range('O2').value = np.round( np.linspace(0, time_horizon, num_timesteps + 1).reshape(-1, 1), 2) percentiles, sample_path = simulate(num_timesteps, num_simulations, starting_price, mu, vol, dt, perc_selection) sht.range('P2').value = percentiles sht.range('S2').value = sample_path
def runVerification(self, instance): # Run simulation update = simulate() if conf.DEBUG: print "Update from verification: \n", update #self.textView.text = update self.updateLabels(update) # Update lebels on GUI ##Plot graphs # Try to remove plots try: self.graph.remove_plot(self.plotPassed) # Remove passed plot self.graph.remove_plot(self.plotFailed) # Remove failed plot self.graphArts.remove_plot( self.plotPassedArts) # Remove passed plot self.graphArts.remove_plot( self.plotFailedArts) # Remove failed plot self.graphSocial.remove_plot( self.plotPassedSocial) # Remove passed plot self.graphSocial.remove_plot( self.plotFailedSocial) # Remove failed plot self.graphScience.remove_plot( self.plotPassedScience) # Remove passed plot self.graphScience.remove_plot( self.plotFailedScience) # Remove failed plot except Exception, e: pass
def run(game): data = pd.io.parsers.read_csv(in_dir + game) players = list(set(data[data['tick'] == 1440]['pid'].dropna())) n_players = len(players) background_dir = bg_dir + game.split('_')[-2] + '/' positions = [] for p in players: sub = data[(data['tick'] == 0) & (data['pid'] == p)] positions += [np.array(sub[['x_pos', 'y_pos']])[0]] out_f = open(out_dir + game, 'w') out_f.write( 'pid,tick,active,x_pos,y_pos,velocity,angle,bg_val,total_points\n') world = simulation.simulate( lambda x: SocialHeuristic(x, watch_others=social_model), background_dir, n_players, par_settings=[0] * len(players), init_pos=positions, out_file=out_f, pids=players) out_f.close()
def run(game): sub = df[df['game'] == game] background_dir = bg_dir + game.split('_')[-2] + '/' n_players = len(sub) pars = list(sub['par']) positions = np.array(sub[['x_pos', 'y_pos']]) pids = list(sub['pid']) out_f = open(out_dir + game, 'w') out_f.write( 'pid,tick,active,x_pos,y_pos,velocity,angle,bg_val,total_points\n') world = simulation.simulate( lambda x: RationalModel(x, watch_others=social_model), background_dir, n_players, par_settings=pars, init_pos=positions, out_file=out_f, pids=pids) out_f.close()
def coordinates(year, month, day): connection = sqlite3.connect("coordinate.db") crsr = connection.cursor() planets = ["Sun", "Mercury", "Venus", "Earth", "Moon", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"] date = datetime.date(year, month, day).isoformat() crsr.execute("SELECT * FROM coordinate WHERE date = ?", (date,)) test = crsr.fetchall() if len(test) == 0: T = planentpos.calc_date(year, month, day, 12, 0, 0) x, y, z = simulation.simulate(T) for i in range(len(planets)): crsr.execute("INSERT INTO coordinate VALUES(?, ?, ?, ?, ?)", (date, planets[i], x[i], y[i], z[i])) xcoords, ycoords, zcoords = [], [], [] for i in range(len(planets)): crsr.execute("SELECT x_coordinate FROM coordinate WHERE date = ? and planet = ?", (date, planets[i])) x_result = crsr.fetchone() xcoords.append(x_result[0]) crsr.execute("SELECT y_coordinate FROM coordinate WHERE date = ? and planet = ?", (date, planets[i])) y_result = crsr.fetchone() ycoords.append(y_result[0]) crsr.execute("SELECT z_coordinate FROM coordinate WHERE date = ? and planet = ?", (date, planets[i])) z_result = crsr.fetchone() zcoords.append(z_result[0]) connection.commit() connection.close() return xcoords, ycoords, zcoords
def __run_basic_example(): import simulation while True: rs = simulation.create_random_example() try: r = simulation.simulate(rs, method=simulation.Euler, step_size=0.005) break except FloatingPointError: continue print(rs._b1) print(r.ys[:3]) print(create_metadata('')) single_animation(r, rs) mtd = [simulation.Euler, simulation.DOPRI5, simulation.ExplicitMidpoint] mms = simulation.simulate_multiple_methods(rs, mtd, duration=20, step_size=0.01) multi_animation(mms, rs) exes = simulation.create_perturbations(5, rs, amount=1e-2) ps = simulation.simulate_multiple_examples(exes, simulation.RK4, 30, 0.005) multi_animation(ps, rs)
def scenario3(): np.random.seed(7) # Simple SIR model. sampler = Sampler() n_days = 365 * 1 population_size = 500_000 I_initial = 500 copenhagen = Region('Copenhagen', population_size, sampler, I_initial, cyclical=2.5) country = Country([copenhagen]) np.random.seed(7) result = simulate(country, n_days=n_days) Plotter.plot_SIR(result) plt.legend() plt.xlabel('Days') plt.tight_layout() plt.savefig(os.path.join(plot_path, '3_SEIR_periodic.png'), dpi=300) plt.show() np.random.seed(7) result = repeat_simulate(country, n_repeats=n_repeats, n_days=n_days) Plotter.plot_intervals(result['I_crit'].copy(), plot_median=False) plt.plot(result['I_crit'][0], '--k', label='Example path', lw=0.5) plt.xlabel('Days') plt.ylabel('# Hospitalized') plt.hlines(copenhagen.population_size * 0.0005, *plt.xlim()) plt.legend() plt.tight_layout() plt.savefig(os.path.join(plot_path, '3_SEIR_periodic_hospitalized.png'), dpi=300) plt.show() sampler = Sampler() n_days = 365 * 4 population_size = 500_000 I_initial = 500 copenhagen = Region('Copenhagen', population_size, sampler, I_initial, cyclical=2.5) country = Country([copenhagen]) np.random.seed(7) result = repeat_simulate(country, n_repeats=n_repeats, n_days=n_days) Plotter.plot_intervals(result['I_crit'].copy(), plot_median=False) plt.plot(result['I_crit'][0], '--k', label='Example path', lw=0.5) plt.xlabel('Days') plt.ylabel('# Hospitalized') plt.hlines(copenhagen.population_size * 0.0005, *plt.xlim()) plt.legend() plt.tight_layout() plt.savefig(os.path.join(plot_path, '3_SEIR_periodic_hospitalized_long.png'), dpi=300) plt.show()
def main(debug: Optional[bool] = False): if not debug: C = float(input("C (нФ) = ")) * 10 ** -9 L = float(input("L (мГн) = ")) * 10 ** -3 Rm = float(input("Rm (Ом) = ")) R0 = float(input("R0 (Ом) = ")) simulation_time = float(input("Simulation time: ")) interval = float(input("Data interval: ")) else: C = 50 * 10 ** -9 L = 10 * 10 ** -3 Rm = 10 R0 = 1 simulation_time = 0.007 interval = 0.000_000_5 circuit = model.OscillatoryCircuit(C, L, Rm, R0) data = simulation.simulate(circuit, simulation_time, interval) print("T (theor.) = {:.7f}".format(circuit.period)) print("T (exp.) = {:.7f}".format(analysis.experimental_period(data))) print("Lambda (theor.) = {:.5f}".format(circuit.lambda_coefficient)) print("Lambda (exp.) = {:.5f}".format(analysis.experimental_lambda(data))) print("Q-factor = {:.5f}".format(circuit.q_factor)) if not path.exists('results'): mkdir('results') plot(1, data.time, data.capacitor_charge, 'Capacitor charge', 'q (Кл)', 'results/charge.png') plot(2, data.time, data.capacitor_voltage, 'Capacitor voltage', 'U (V)', 'results/voltage.png') plot(3, data.time, data.capacitor_current, 'Capacitor current', 'I (A)', 'results/current.png') if not debug: pyplot.show()
def simulate_season(numGames): numSuccessfulPredictions = 0 with open('2017gamelogs.txt', 'r') as infile, open('2017simulations.txt', 'w') as outfile: outfile.write( "index,awayTeam,winAway,runAway,homeTeam,winHome,runHome," + "predictedWinner,actualWinner,numSuccessfulPredictions\n") for index, line in enumerate(infile, start=1): gameInfo = [x.strip('\"') for x in line.split(',')] # store (retrosheet player id, player name) tuples batterInfoListAway = [] batterInfoListHome = [] for i in range(106, 133, 3): batterName = get_fangraphs_name(gameInfo[i]) batterInfoListAway.append((gameInfo[i - 1], batterName)) for i in range(133, 159, 3): batterName = get_fangraphs_name(gameInfo[i]) batterInfoListHome.append((gameInfo[i - 1], batterName)) pitcherInfoAway = (gameInfo[101], get_fangraphs_name(gameInfo[102])) pitcherInfoHome = (gameInfo[103], get_fangraphs_name(gameInfo[104])) # store batter, pitcher and league objects batterListAway = [] batterListHome = [] for batterInfoAway, batterInfoHome in zip(batterInfoListAway, batterInfoListHome): batterListAway.append( get_correct_batter_object(batterInfoAway)) batterListHome.append( get_correct_batter_object(batterInfoHome)) pitcherAway = get_correct_pitcher_object(pitcherInfoAway) pitcherHome = get_correct_pitcher_object(pitcherInfoHome) league = League.objects.get(year=2017) winAway, winHome, runAway, runHome = simulation.simulate( numGames, batterListAway, pitcherAway, batterListHome, pitcherHome, league) predictedWinner = 'Home' if winAway > winHome: predictedWinner = 'Away' actualWinner = 'Home' # if the away team won in the actual game if int(gameInfo[9]) > int(gameInfo[10]): actualWinner = 'Away' if predictedWinner == actualWinner: numSuccessfulPredictions += 1 print(index) # index, winAway, winHome, predictedWinner, actualWinner, numSuccessfulPredictions outfile.write( str(index) + ',' + gameInfo[3] + ',' + str(winAway) + ',' + str(runAway) + ',' + gameInfo[6] + ',' + str(winHome) + ',' + str(runHome) + ',' + predictedWinner + ',' + actualWinner + ',' + str(numSuccessfulPredictions) + '\n')
def run_simulation(): data = request.get_json(force=True) # User Inputs num_simulations = int(data['num_simulations']) time_horizon = float(data['time_horizon']) num_timesteps = int(data['num_timesteps']) dt = time_horizon / num_timesteps # Length of time period vol = float(data['vol']) / 100 mu = np.log(1 + float(data['exp_simple_ret']) / 100) # Drift starting_price = float(data['starting_price']) perc_selection = [5, 50, 95] percentiles, sample_path = simulate(num_timesteps, num_simulations, starting_price, mu, vol, dt, perc_selection) x = np.round(np.linspace(0, time_horizon, num_timesteps + 1), 2).tolist() data = [{ 'x': x, 'y': percentiles[:, i].tolist(), 'name': '{0}th Percentile'.format(perc_selection[i]) if perc_selection[i] != 50 else 'Median' } for i in range(percentiles.shape[1])] data.append({ 'x': x, 'y': sample_path.squeeze().tolist(), 'name': 'Sample Path' }) return json.dumps(data)
def runCautious(filename, num_exp): first = True for hero_mode in [2, 4, 5]: for p_d in range(5, 20 + 1, 5): p_d /= 100 if hero_mode == 5: real_mode = 2 p_r_a = pra[str(p_d)] inputs, data = s.simulate(real_mode, num_exp, probDetect=p_d, probRandAttack=p_r_a) inputs["hero_mode"] = 5 else: inputs, data = s.simulate(hero_mode, num_exp, probDetect=p_d) dataToCSV(filename, inputs, data, first) first = False
def get(self): years = int(self.get_argument('years', 10)) iterations = int(self.get_argument('iterations', 2)) rows = simulation.simulate(years, iterations) forecast_id = rows[0][0] self.render('templates/simulation.html', years=years, iterations=iterations, rows=rows, forecast_id=forecast_id)
def update(self): """ Update the simulation if something was changed in the input, according to the data from the UI. """ if self.update_simulation: time_dir_right_step = -self.time_step if self.time < 0.0 else self.time_step self.orbits = simulation.simulate( self.grav_const_slider.val, map(simulation.from_obj, self.objs), self.time, time_dir_right_step ) self.update_simulation = False
def runVerification(self, instance): # Run simulation update = simulate() if conf.DEBUG: print "Update from verification: \n", update #self.textView.text = update self.updateLabels(update) # Update lebels on GUI ##Plot graphs # Try to remove plots try: self.graph.remove_plot(self.plotPassed) # Remove passed plot self.graph.remove_plot(self.plotFailed) # Remove failed plot self.graphArts.remove_plot(self.plotPassedArts) # Remove passed plot self.graphArts.remove_plot(self.plotFailedArts) # Remove failed plot self.graphSocial.remove_plot(self.plotPassedSocial) # Remove passed plot self.graphSocial.remove_plot(self.plotFailedSocial) # Remove failed plot self.graphScience.remove_plot(self.plotPassedScience) # Remove passed plot self.graphScience.remove_plot(self.plotFailedScience) # Remove failed plot except Exception, e: pass
def run_simulation(): sht = xw.Book.caller().sheets[0] # User Inputs num_simulations = sht.range('E3').options(numbers=int).value time_horizon = sht.range('E4').value num_timesteps = sht.range('E5').options(numbers=int).value dt = time_horizon / num_timesteps # Length of time period vol = sht.range('E7').value mu = np.log(1 + sht.range('E6').value) # Drift starting_price = sht.range('E8').value perc_selection = [5, 50, 95] # Excel: clear output, write out initial values of percentiles/sample path and set chart source and x-axis values sht.range('O2').expand().clear_contents() sht.range('P2').value = [starting_price, starting_price, starting_price, starting_price, perc_selection] sht.charts['Chart 5'].set_source_data(sht.range((1, 15), (num_timesteps + 2, 19))) sht.range('O2').value = np.round(np.linspace(0, time_horizon, num_timesteps + 1).reshape(-1, 1), 2) percentiles, sample_path = simulate(num_timesteps, num_simulations, starting_price, mu, vol, dt, perc_selection) sht.range('P2').value = percentiles sht.range('S2').value = sample_path
''' Documentation, License etc. @package pltsim ''' import argparse from simulation import simulate def parseArgs(): argParser = argparse.ArgumentParser(description = "Simpulate TCP and AQM algorithms on arbitary topology.") argParser.add_argument("-c", "--capacity", type = int, default = 100, help = "capacity of all links in packets per second") argParser.add_argument("-t", "--tcp", required = True, choices = ["Reno"], help = "tcp algorithm name") argParser.add_argument("-a", "--aqm", required = True, choices = ["RED", "CoDel"], help = "aqm algorithm name") argParser.add_argument("-r", "--routes", required = True, type = argparse.FileType('r'), help = "file with flow routes\neach line has a chain of routers indexes, which represents a flow") argParser.add_argument("-o", "--output", required = True, type = argparse.FileType('w'), help = "output file, where NS3 stores its log after execution") return argParser.parse_args() def parseRoutes(routesFile): routes = [] for line in routesFile: routes.append([int(routerIndex) for routerIndex in line.strip().split(' ')]) return routes if __name__ == "__main__": args = parseArgs() args.routes = parseRoutes(args.routes) simulate(args.routes, args.tcp, args.aqm, args.capacity, args.output)
import simulation if __name__ == '__main__': # simulation.simulate(int(input("observation_period (s): \n")), # int(input("max_driveway_length (cars): \n")), # int(input("average_arrival_rate (s): \n")), # int(input("average_service_rate (s): \n")), # int(input("average_meal_price ($): \n")), # float(input("per_meal_cost ($): \n"))) simulation.simulate()
# W_E_LGN_E_L6 = exponential_connect(0.2/100000., n_e_lgn, n_e_l6) # W_E_LGN_I_L6 = exponential_connect(0.2/1000000., n_e_lgn, n_i_l6) #Backup W_E_LGN_E_L6 = exponential_connect(2/100000., n_e_lgn, n_e_l6) W_E_LGN_I_L6 = exponential_connect(2/1000000., n_e_lgn, n_i_l6) W_E_L6_E_LGN = exponential_connect(0.4375/100000., n_e_l6, n_e_lgn) # 4 mv / 10 (Wang & Hirsch 2010) 300 pA (Granseth & Lindstrom 2002) # TODO: isn't it Wnag & Hirsch 2011? # TODO: E_L6 is NOT connected to I_LGN. Find reference # Backup W_E_L4_E_L6 = exponential_connect(4/100000., n_e_l4, n_e_l6) # PSP = 1.4 mV Haeusler and Maass 2006 (heuristic from E L2/3 to E L5) # W_E_L4_E_L6 = exponential_connect(0.5/100000., n_e_l4, n_e_l6) # W_E_L6_TRN = exponential_connect(0.4/1000000., n_e_l6, n_trn) #Backup W_E_L6_TRN = exponential_connect(4/1000000., n_e_l6, n_trn) W_E_L4_TRN = W_E_L6_TRN # only if net include V1 L4 but not V1 L6 simulate(nruns, total_time, with_V1_L4, with_V1_L6, with_TRN, input, con_input_lgn, n_e_lgn, n_i_lgn, n_e_l6, n_i_l6, n_e_l4, n_i_l4, n_trn, delay_distbtn_E_L6_LGN, delay_E_L4_E_LGN, delay_E_LGN_I_L4, delay_E_LGN_E_L4, delay_E_LGN_E_L6, delay_E_LGN_TRN, delay_E_L4_TRN, delay_distbtn_E_L6_TRN, delay_E_LGN_I_LGN, delay_I_LGN_E_LGN, delay_E_LGN_I_L6, lgn_params, l4_params, l6_params, W_TRN_TRN, W_E_LGN_TRN, W_TRN_E_LGN, W_E_L6_TRN, W_E_L4_E_L6, W_E_LGN_E_L4, W_E_L4_E_LGN, W_E_L6_E_LGN, W_E_LGN_E_L6, W_E_LGN_I_L6, W_E_LGN_I_L4, W_E_L4_TRN, connect_E_LGN_E_L4, connect_E_LGN_I_L4, connect_E_L4_E_LGN, connect_E_LGN_I_L6, connect_E_LGN_E_L6, connect_E_L6_E_LGN, connect_E_L4_TRN, connect_E_L6_TRN, connect_E_LGN_TRN, connect_TRN_E_LGN, connect_E_L4_E_L6) plt.show()
import os import fake import simulation import display from groups.sim_group_move import generate_fake option = raw_input('0. Real data \n1. Generated data\n') if option == '0': fake.process('generated.dat') simulation.simulate('generated.dat') display.display('generated-display.dat') elif option == '1': generate_fake(os.path.join(os.getcwd(), 'data','fake-virus.dat')) simulation.simulate('fake-virus.dat') display.display('fake-virus-display.dat') else: print 'Invalid option'
from pprint import pprint from simulation import simulate import json import sys materialParameters = [1.0, 5.0, 10.0, 5.0] resultsFileName = "results.json" if len(sys.argv) >= 5: materialParameters = [float(sys.argv[1]), float(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4])] if len(sys.argv) == 6: resultsFileName = sys.argv[5] resultsFibre = simulate(0.0, materialParameters) # by re-orienting the fibre direction in the unit cube we can simulate a cross fibre extension resultsCross = simulate(90.0, materialParameters) results = {} results["materialParameters"] = materialParameters results["fibre"] = resultsFibre results["cross"] = resultsCross pprint(resultsFibre) pprint(resultsCross) pprint(results) with open(resultsFileName, 'w') as rjson: json.dump(results, rjson)
[weight, weight, 0, weight], # E-E I-I E-I [weight, 0, weight, weight], # E-E I-E E-I [0, weight, weight, weight], # I-I I-E E-I [weight, weight, weight, weight] # E-E I-I I-E E-I ] time_sim_start = str(datetime.now()) fname_peaks = os.path.join(OUTPUT_DIR, "sweep_" + time_sim_start + ".txt") open(fname_peaks, 'a').close() for conn in connectivity: lgn_params = { 'w_e_lgn_e_lgn': exponential_connect(conn[0], n_e_lgn, n_e_lgn, False), # TODO: reference for this -> LGN doesn't have intrinsic connections 'w_i_lgn_i_lgn': exponential_connect(conn[1], n_i_lgn, n_i_lgn, False), # TODO: reference for this -> LGN doesn't have intrinsic connections 'w_i_lgn_e_lgn': exponential_connect(conn[2], n_i_lgn, n_e_lgn), # PSP 5 mV (Wang & Hirsch 2010) 'w_e_lgn_i_lgn': exponential_connect(conn[3], n_e_lgn, n_i_lgn), 'delay_e_i': 1, 'delay_i_e': 1 } fname_lfps_prefix = os.path.join(OUTPUT_DIR, time_sim_start + "_" + str(conn) + "_sim-") print conn simulate(conn, OUTPUT_DIR, fname_peaks, fname_lfps_prefix, dt, nruns, total_time, temperature, with_V1_L4, with_V1_L6, with_TRN, input, con_input_lgn, n_e_lgn, n_i_lgn, n_e_l6, n_i_l6, n_e_l4, n_i_l4, n_trn, threshold, delay, delay_distbtn_E_L6_LGN, delay_E_L4_E_LGN, delay_E_LGN_I_L4, delay_E_LGN_E_L4, delay_E_LGN_E_L6, delay_E_LGN_TRN, delay_E_L4_TRN, delay_distbtn_E_L6_TRN, delay_E_LGN_I_L6, lgn_params, l4_params, l6_params, trn_params, W_E_LGN_TRN, W_TRN_E_LGN, W_E_L6_TRN, W_E_L4_E_L6, W_E_LGN_E_L4, W_E_L4_E_LGN, W_E_L6_E_LGN, W_E_LGN_E_L6, W_E_LGN_I_L6, W_E_LGN_I_L4, W_E_L4_TRN, connect_E_LGN_E_L4, connect_E_LGN_I_L4, connect_E_L4_E_LGN, connect_E_LGN_I_L6, connect_E_LGN_E_L6, connect_E_L6_E_LGN, connect_E_L4_TRN, connect_E_L6_TRN, connect_E_LGN_TRN, connect_TRN_E_LGN, connect_E_L4_E_L6)
import viz import simulation results = simulation.simulate() viz.phase_3D(results,'population','food','wood') viz.phase_2D(results,'food','wood')
def optimize(u_method, obs, **kwargs): ''' optimization function coords - spot where the function is evaluated f - result of the evaluation ''' Point = namedtuple("point", ["x", "y"]) y = kwargs['y'] sim_n = kwargs['sim_n'] output = dict() cpustart = timeit.default_timer() # some decision procedure that results in the x y result if u_method is 'golden': # deterministic/non evaluating parts simtime = 0 alpha = kwargs['alpha'] epsilon = kwargs['epsilon'] a = kwargs['a'] b = kwargs['b'] output['a'] = a output['b'] = b c = b + (a - b)/golden ob_c = Point(x=c, y=y) d = a + (b - a)/golden ob_d = Point(x=d, y=y) pick = None # sample and confidence loop # 1. check if either f(c) or f(d) exists. if not, create them. # 2 samples are needed to establish a CI # if they do exist, sample only from the larger CI explored = True if ob_c not in obs: explored = False csim = simulate(c, y, sim_n=sim_n) simtime += csim['simtime'] obs[ob_c] = [csim['f']] csim = simulate(c, y, sim_n=sim_n) simtime += csim['simtime'] obs[ob_c].append(csim['f']) if ob_d not in obs: explored = False dsim = simulate(d, y, sim_n=sim_n) simtime += dsim['simtime'] obs[ob_d] = [dsim['f']] dsim = simulate(d, y, sim_n=sim_n) simtime += dsim['simtime'] obs[ob_d].append(dsim['f']) # Compute confidence intervals (prerequisite for future steps) ci_c = stats.norm.interval( alpha, loc=np.mean(obs[ob_c]), scale=np.std(obs[ob_c], ddof=1)/np.sqrt(len(obs[ob_c]))) ci_d = stats.norm.interval( alpha, loc=np.mean(obs[ob_d]), scale=np.std(obs[ob_d], ddof=1)/np.sqrt(len(obs[ob_d]))) if explored: if (ci_c[1] - ci_c[0]) > (ci_d[1] - ci_d[0]): csim = simulate(c, y, sim_n=sim_n) simtime += csim['simtime'] obs[ob_c].append(csim['f']) ci_c = stats.norm.interval( alpha, loc=np.mean(obs[ob_c]), scale=np.std(obs[ob_c], ddof=1)/np.sqrt(len(obs[ob_c]))) else: dsim = simulate(d, y, sim_n=sim_n) simtime += dsim['simtime'] obs[ob_d].append(dsim['f']) ci_d = stats.norm.interval( alpha, loc=np.mean(obs[ob_d]), scale=np.std(obs[ob_d], ddof=1)/np.sqrt(len(obs[ob_d]))) # 2. while confidence intervals are not disjoint, keep shrinking em while (ci_c[1] >= ci_d[0]) and (ci_d[1] >= ci_c[0]): # exit condition: both CIs are so small we are indifferent if max(ci_c[1] - ci_c[0], ci_d[1] - ci_d[0]) < epsilon: break if (ci_c[1] - ci_c[0]) > (ci_d[1] - ci_d[0]): csim = simulate(c, y, sim_n=sim_n) simtime += csim['simtime'] obs[ob_c].append(csim['f']) ci_c = stats.norm.interval( alpha, loc=np.mean(obs[ob_c]), scale=np.std(obs[ob_c], ddof=1)/np.sqrt(len(obs[ob_c]))) else: dsim = simulate(d, y, sim_n=sim_n) simtime += dsim['simtime'] obs[ob_d].append(dsim['f']) ci_d = stats.norm.interval( alpha, loc=np.mean(obs[ob_d]), scale=np.std(obs[ob_d], ddof=1)/np.sqrt(len(obs[ob_d]))) # 3. now that CIs are disjoint, take the lower one # case: confidence interval at c is fully below interval at d if ci_c[1] < ci_d[0]: pick = 'c' # case: confidence interval at d is fully below interval at c if ci_d[1] < ci_c[0]: pick = 'd' if pick is 'c': output['b'] = d else: output['a'] = c output['f_c'] = np.mean(obs[ob_c]) output['f_d'] = np.mean(obs[ob_d]) # end loop output['simtime'] = simtime # *** if u_method is 'gradient': simout = simgradient( kwargs['x'], kwargs['y'], sim_grad_n=kwargs['sim_grad_n']) output['gradient'] = simout['gradient'] output['x'] = kwargs['x'] - kwargs['stepsize'] * output['gradient'] output['simtime'] = simout['simtime'] simout = simulate( output['x'], kwargs['y'], sim_n=sim_n) output['f'] = simout['f'] output['simtime'] += simout['simtime'] # *** # end decision procedure output['opttime'] = timeit.default_timer() - cpustart - output['simtime'] return output