def experiment(servers_count): print("Starting simulation with %d servers" % servers_count) simulation = Simulation() avg_time = simulation.start(servers_count) print("-------------------") print() return servers_count, avg_time
def test_categories_affect(is_stochastic: bool = False): print("\nprinting protocols comparison:\n") people_per_simulation = 100_000 consts = Consts(positive_tests_percent=2) print(consts) green = Simulation(consts, TestPolicies.GREEN, people_per_simulation, is_stochastic=is_stochastic) yellow = Simulation(consts, TestPolicies.YELLOW, people_per_simulation, is_stochastic=is_stochastic) orange = Simulation(consts, TestPolicies.ORANGE, people_per_simulation, is_stochastic=is_stochastic) red = Simulation(consts, TestPolicies.RED, people_per_simulation, is_stochastic=is_stochastic) print(f"green: {green.infected} \nyellow : {yellow.infected} \norange : {orange.infected} \nred : {red.infected}")
class Window(pyglet.window.Window): def __init__(self, map_file, config_file): super().__init__(resizable=True, caption='Tourism Simulation', visible=False) self.set_minimum_size(640, 480) self.set_maximum_size(2260, 3540) self.frame_rate = 1 / 60.0 # Target frame-rate, usually can't keep up self.icon1 = pyglet.image.load('./graphics/Icon1.png') self.icon2 = pyglet.image.load('./graphics/Icon2.png') self.set_icon(self.icon1, self.icon2) self.map = Map(self.width, self.height, map_file) self.set_visible(True) self.x = 800 self.y = -800 self.simulation = Simulation(2260, 3540, self.width, self.height, config_file) def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): if (buttons & mouse.LEFT) or (buttons & mouse.MIDDLE): self.x = self.x + dx self.y = self.y + dy if self.x > 1120: self.x = 1120 pass if self.x < self.width - 1120: self.x = self.width - 1120 pass if self.y > 1760: self.y = 1760 pass pass if self.y < self.height - 1760: self.y = self.height - 1760 pass def update(self, dt): self.simulation.update(dt) def on_draw(self): self.clear() self.map.draw(self.width, self.height, self.x, self.y) self.simulation.draw(self.x, self.y, self.width, self.height)
def __init__(self, map_file, config_file): super().__init__(resizable=True, caption='Tourism Simulation', visible=False) self.set_minimum_size(640, 480) self.set_maximum_size(2260, 3540) self.frame_rate = 1 / 60.0 # Target frame-rate, usually can't keep up self.icon1 = pyglet.image.load('./graphics/Icon1.png') self.icon2 = pyglet.image.load('./graphics/Icon2.png') self.set_icon(self.icon1, self.icon2) self.map = Map(self.width, self.height, map_file) self.set_visible(True) self.x = 800 self.y = -800 self.simulation = Simulation(2260, 3540, self.width, self.height, config_file)
def run(window_size): pygame.init() cells = {} camera = Camera(window_size, cells) Cell.static_init(camera, cells) simulation = Simulation(camera, cells) clock = pygame.time.Clock() debug_mode = False while True: dt = clock.tick(FPS) / 1000 for event in pygame.event.get(): if event.type == pygame.QUIT: return elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: return elif event.key == pygame.K_F1: debug_mode = not debug_mode camera.process_event(event) simulation.process_event(event) camera.update(dt) simulation.update(dt) camera.draw() if debug_mode: show_debug_info(camera, simulation, clock.get_fps()) pygame.display.flip()
def run_experiment(self): xmax = self.simulation_params.wall.get_xmax() ymax = self.simulation_params.wall.get_ymax() rc = self.simulation_params.interaction.get_rc() v0 = self.simulation_params.params.v0 mu = self.simulation_params.params.mu deltat = self.simulation_params.params.deltat diffcoef = self.simulation_params.params.diffcoef sim_steps = self.simulation_params.simulation_steps interaction = self.simulation_params.interaction wall = self.simulation_params.wall init_positions = self.simulation_params.init_positions epsilon = self.simulation_params.params.epsilon sigma = self.simulation_params.params.sigma max_lambda = self.max_lambda if self.max_lambda is not None else min( xmax, ymax) / rc - 1 the_lambdas = np.linspace(0, max_lambda, self.lambda_samples) times = [] for lambd in the_lambdas: rv = (1 + lambd) * rc params = Params(rc=rc, rv=rv, v0=v0, mu=mu, deltat=deltat, diffcoef=diffcoef, epsilon=epsilon, sigma=sigma) sim = Simulation(sim_steps, interaction, wall, init_positions, params) sim.run() times.append(sim.total_phys_time) return the_lambdas, np.array(times)
def setUpClass(cls): cls.tempf = "./temp.test_sim" cls.runlog = "log.screen" cls.obj = Simulation(".") cls.string = "echo 0 1.1" cls.stdout = sys.stdout cls.stderr = sys.stderr #TODO stderr not right now although test_run passed. sys.stdout = cStringIO.StringIO() sys.stderr = cStringIO.StringIO() #if os.name == "nt": # string = "type 0 1.1 > res.preprocess" #else: # string = "echo 0 1.1 > res.preprocess" with open(cls.tempf, "wt") as f: f.write(cls.string)
def initiate_simulation(self, var): simulation = Simulation.Simulation() simulation.set_selected_virus(next(filter(lambda x: x.get_name() == var, self._virus_list))) simulation.set_mobility_reduction_start_time( self._mainWindow.get_rootWidget().sP_reduce_mobility_start.value()) simulation.set_people_moving_distance_per_day_after_reduction( self._mainWindow.get_rootWidget().sB_reduced_mobility.value()) simulation.set_people_moving_distance_per_day( self._mainWindow.get_rootWidget().sB_init_population_moving_distance.value()) simulation.set_population_size(self._mainWindow.get_rootWidget().sB_simulation_population.value()) simulation.set_initial_infected_population( self._mainWindow.get_rootWidget().sB_init_infected_population.value()) simulation.set_send_to_hospital_day(self._mainWindow.get_rootWidget().sP_send_to_hospital_day.value()) simulation.set_hospital_capacity(self._mainWindow.get_rootWidget().sB_hospital_capacity.value()) simulation.run_simulation()
def test_random_distribution(self, mocked_randint): c = Character() simulation = Simulation( Evaluator(actors=[c], rules=[ Rule('rule1', [], [Predicate('p1', 0)], prob=1), Rule('rule2', [], [Predicate('p2', 0)], prob=4) ])) mocked_randint.return_value = 1 simulation.step() self.assertStateContains(PredicateInstance('p1', c), simulation.evaluator) self.assertStateDoesNotContain(PredicateInstance('p2', c), simulation.evaluator) mocked_randint.return_value = 2 simulation.step() self.assertStateContains(PredicateInstance('p1', c), simulation.evaluator) self.assertStateContains(PredicateInstance('p2', c), simulation.evaluator)
# -*- coding:utf-8 -*- path_til = 'C:\\til\\' path_pension = 'C:\\Til-Pension\\' path_liam = 'C:\\liam2\\' import sys sys.path.append(path_liam) from src.simulation import Simulation path_model = 'console.yml' simulation = Simulation.from_yaml(path_model, input_dir = None, input_file = None, output_dir = path_til + 'output', output_file = None) simulation.run(False)
--si: Simulation Simulate the available scenarios --pl: Plotter Plot the generated results ''' TASKS = { 'cd': CleanData(), 'cm': ContextMapping(), 'cl': ContextLook(), 'ge': Generator(), 'ro': RouteMiner(), 'tm': TrafficMiner(), 'fm': FlowManager(), 'si': Simulation(), 'pl': Plotter() } class Ring: def main(self, args): global TASKS print('!##### Initiated with args: {0}'.format(args)) if args.cd: print('!### Task: cd') call = TASKS['cd'] call.main() if args.cm:
default=None, help='initial coordinates file') parser.add_argument('--r', type=str, default="restrt", help='') parser.add_argument('--x', type=str, default="mdcrd", help='') parser.add_argument('--o', type=str, default="mdout", help="") parser.add_argument('--box', type=str, default="mdbox", help='') parser.add_argument('--device_id', type=int, default=0, help='') args_opt = parser.parse_args() context.set_context(mode=context.GRAPH_MODE, device_target="GPU", device_id=args_opt.device_id, save_graphs=False) if __name__ == "__main__": simulation = Simulation(args_opt) start = time.time() compiler_time = 0 save_path = args_opt.o file = open(save_path, 'w') for steps in range(simulation.md_info.step_limit): print_step = steps % simulation.ntwx if steps == simulation.md_info.step_limit - 1: print_step = 0 temperature, total_potential_energy, sigma_of_bond_ene, sigma_of_angle_ene, sigma_of_dihedral_ene, \ nb14_lj_energy_sum, nb14_cf_energy_sum, LJ_energy_sum, ee_ene, _ = simulation(Tensor(steps), Tensor(print_step)) if steps == 0: compiler_time = time.time() if steps % simulation.ntwx == 0 or steps == simulation.md_info.step_limit - 1: if steps == 0: print(
"Parameters Output": paraTableFile, "Simulation Folder": path, "Post-Process": processScript, } print_info(INFO_DICT) ( paraArrayInitial, paraTable, ) = initialize_parameters(initParaTableFile, paraTableFile, ffFile=ffForSimulation, ffTemp=ffTemplate) properties = initialize_properties(propertyNames, propertyRefs, propertySpecials, int(totalProperties)) simulation = Simulation(path, processScript) # ----------------------------------------------------------------------- # def test_flow_with_1_arg(p): return test_flow(p, paraTable, properties) def simulation_with_1_arg(p): return simulation_flow(p, paraTable, simulation, properties) #TODO wrap this part as a function and give 'func' as input? print("\nOptimizing...:") if mode == "test": func = test_flow_with_1_arg elif mode == "simulation": func = simulation_with_1_arg
from src.simulation import Simulation simulation = Simulation() simulation.run()
pts3 = np.column_stack([XX.ravel(), YY.ravel()]) print("Numero de particulas = %d" % len(pts3)) rc = interaction.get_rc() lambd = 0.2 rv = (1+lambd)*rc v0 = 1 mu = 1 deltat = 0.1 diffcoef = 1 params = Params(rc=rc, rv=rv, v0=v0, mu=mu, deltat=deltat, diffcoef=diffcoef, epsilon=epsilon, sigma=sigma) sim = Simulation(sim_steps, interaction, wall, pts3, params) grid_rows = sim.particle_handlers.grid.rows grid_cols = sim.particle_handlers.grid.cols results = sim.run() print("Tiempo\t\t\t\t\t\t\t\t\tsegundos") print("Total limpiar grilla\t\t\t\t\t%.5f" % sim.acc_ctime) print("Total asignar en grilla\t\t\t\t\t%.5f" % sim.acc_asstime) print("Total crear verlet\t\t\t\t\t\t%.5f" % sim.acc_vtime) print("Total calcular interacciones\t\t\t%.5f" % sim.acc_interaction_time) print("Total calcular paso\t\t\t\t\t\t%.5f" % sim.acc_calc_step_time) print("Total ejecucion\t\t\t\t\t\t\t%.5f" % sim.total_phys_time) if sim.c_ctime > 0: print("Promedio limpiar grilla\t\t\t\t\t%.5f" % float(sim.acc_ctime/sim.c_ctime)) if sim.c_asstime > 0:
params_tuple = [lambd, eta, total_phys_time, wall_to_use.name(), sigma, epsilon, v0, deltat, all_interactions, particles_num] params_tuple_str = [] for x in params_tuple: if type(x) == float: params_tuple_str.append("%.4f" % x) else: params_tuple_str.append(str(x)) fname = 'result_' + '_'.join(params_tuple_str) + '_.txt' wall = wall_to_use(xmin, xmax, ymin, ymax) rv = (1+lambd)*rc params = Params(rc=rc, rv=rv, v0=v0, mu=mu, deltat=deltat, diffcoef=diffcoef, epsilon=epsilon, sigma=sigma) sim = Simulation(total_phys_time, interaction, wall, init_positions, params) grid_rows = sim.particle_handlers.grid.rows grid_cols = sim.particle_handlers.grid.cols results = sim.run() sim_time = sim.total_run_time with open(fname, 'w') as f: f.write(str(sim_time)) if save_results: pkfile = fname + '_positions.pkl' with open(pkfile, 'wb') as f: pickle.dump(results, f, pickle.HIGHEST_PROTOCOL)
def Sim(): sim = Simulation() sim.run()
lines = [name, wins, fails, percents] handler.write(" \n".join(lines) + "\n\n") handler.flush() print(lines) simulations = [] simulationsS1R = [ Simulation( t=15, total_time=100, width=10, height=10, obstacle_percent=10, dirty_percent=10, robot_count=1, robot_factory=lambda p: ReactiveRobot(p), baby_count=4, baby_factory=lambda p: Baby(p), ) for _ in range(30) ] simulationsS2R = [ Simulation( t=15, total_time=100, width=10, height=10, obstacle_percent=20, dirty_percent=10,
def print_categories_boundaries(people_per_simulation: int = 100_000, R0_low: float = 1.0, R0_high: float = 3, is_stochastic: bool = True): print("\nprinting categories boundaries:\n") def print_color_range(color: str, low_simulation: Simulation, high_simulation: Simulation): print(f"\ncategory {color} boundaries:\n" f"incoming sicks: \t {low_simulation.initial_patients} - {high_simulation.initial_patients}\n" f"first circles infections: \t {low_simulation.infected} - {high_simulation.infected}") # green min_percent = 0 max_percent = 1 green_min_consts = Consts(positive_tests_percent=min_percent, R0=R0_low) green_min = Simulation(green_min_consts, TestPolicies.GREEN, people_per_simulation, is_stochastic=is_stochastic) green_max_consts = Consts(positive_tests_percent=max_percent, R0=R0_high) green_max = Simulation(green_max_consts, TestPolicies.GREEN, people_per_simulation, is_stochastic=is_stochastic) print_color_range("green", green_min, green_max) # yellow min_percent = 1 max_percent = 5 yellow_min_consts = Consts(positive_tests_percent=min_percent, R0=R0_low) yellow_min = Simulation(yellow_min_consts, TestPolicies.YELLOW, people_per_simulation, is_stochastic=is_stochastic) yellow_max_consts = Consts(positive_tests_percent=max_percent, R0=R0_high) yellow_max = Simulation(yellow_max_consts, TestPolicies.YELLOW, people_per_simulation, is_stochastic=is_stochastic) print_color_range("yellow", yellow_min, yellow_max) # orange min_percent = 5
# -*- coding:utf-8 -*- from til.CONFIG import path_liam, path_model, path_pension import sys import os from til import __path__ as path_til sys.path.append(path_liam) sys.path.append(path_pension) from src.simulation import Simulation fichier = path_model + '\\til_base_model\console.yml' output_dir = os.path.join(path_til[0], 'output') simulation = Simulation.from_yaml( fichier, input_dir = None, input_file = None, output_dir = output_dir, output_file = None) simulation.run(False) # import cProfile # command = """simulation.run(False)""" # cProfile.runctx( command, globals(), locals(), filename="OpenGLContext.profile1")
# -*- coding:utf-8 -*- from CONFIG import path_liam, path_til, path_model import sys sys.path.append(path_liam) from src.simulation import Simulation fichier = path_model + 'console.yml' simulation = Simulation.from_yaml( fichier, input_dir = None, input_file = None, output_dir = path_til + 'output', output_file = None) simulation.run(False) # import cProfile # command = """simulation.run(False)""" # cProfile.runctx( command, globals(), locals(), filename="OpenGLContext.profile1")
from src.mathematics import Segment, Vector from src.physics.mechanics import Particle from src.physics.optics import PlaneMirror from src.physics.world import World from src.simulation import Simulation w = World((800, 600)) m = 1. w.add_particle(Particle(Vector(0., 0.), Vector(10, 10), m)) w.mirrors.append(PlaneMirror(Segment((0, 150), (200, 0)))) w.mirrors.append(PlaneMirror(Segment((650, 0), (800, 150)))) w.mirrors.append(PlaneMirror(Segment((650, 600), (800, 450)))) w.mirrors.append(PlaneMirror(Segment((0, 450), (200, 600)))) Simulation(w).run()
else: # if has another owner, pay rent operation_ok = player.pay_rent_to_owner(prop) if not operation_ok: board.remove_player_properties(player) if not board.at_least_two_playing(): break # print("\nGame Over!") return board.declare_winner() if __name__ == '__main__': simulation = Simulation() simulations_qty = 300 for game in range(simulations_qty): print('Starting Simulation {}'.format(game+1)) winner, final_round = start_game() simulation.winner = winner simulation.round_per_game = final_round print('\n\nTodas as simulacoes foram finalizadas!') print('\n\nResumo:') time_out_qty = simulation.count_round_per_game(1000) print('{0} partidas terminam por time out (1000 rodadas).'.format(time_out_qty)) round_avg = simulation.round_avg()
#wall = WallA(xmin, xmax, ymin, ymax) wall = WallPeriodicBC(xmin, xmax, ymin, ymax) X_u = np.linspace(xmin + rc, xmax - rc, 6) Y_u = np.linspace(ymin + rc, ymax - rc, 6) XX, YY= np.meshgrid(X_u, Y_u) pts = np.vstack([XX.ravel(), YY.ravel()]) pts3 = np.column_stack([XX.ravel(), YY.ravel()]) print("Numero de particulas = %d" % len(pts3)) params = Params(rc=rc, rv=rv, v0=v0, mu=mu, deltat=deltat, diffcoef=diffcoef, epsilon=epsilon, sigma=sigma) sim = Simulation(total_phys_time, interaction, wall, pts3, params, all_interactions=all_interactions, save_interactions_idxs=True, save_point_to_point=True) xsize = 1024 ysize = 1024 margin = 50 results = [] all_angles = [] all_interactions_list = [] for result, angles, interactions in sim.run_gen(): results.append(np.copy(result)) all_angles.append(np.copy(angles)) all_interactions_list.append(np.copy(interactions))
type=bool, default=False, help='If use mdnn to update the atom charge') parser.add_argument('--checkpoint', type=str, default="", help='Checkpoint file') args_opt = parser.parse_args() context.set_context(mode=context.GRAPH_MODE, device_target="GPU", device_id=args_opt.device_id, save_graphs=False) if __name__ == "__main__": simulation = Simulation(args_opt) if args_opt.u and args_opt.checkpoint: net = Mdnn() load_checkpoint(args_opt.checkpoint, net=net) transcrd = TransCrdToCV(simulation) start = time.time() compiler_time = 0 save_path = args_opt.o simulation.Main_Initial() for steps in range(simulation.md_info.step_limit): print_step = steps % simulation.ntwx if steps == simulation.md_info.step_limit - 1: print_step = 0 temperature, total_potential_energy, sigma_of_bond_ene, sigma_of_angle_ene, sigma_of_dihedral_ene, \ nb14_lj_energy_sum, nb14_cf_energy_sum, LJ_energy_sum, ee_ene, _ = simulation(Tensor(steps), Tensor(print_step))