def main(args): seed = args.seed if args.seed is not None else secrets.randbits(32) capabilities = [ Capability(f"C{n}", args.task_period, n) for n in range(args.num_capabilities) ] choose = get_agent_choose_behaviour(args.agent_choose) agent_behaviours = [[behaviour] * num_agents for (num_agents, behaviour) in args.agents] # Assume that each agent has all capabilities agents = [ Agent(f"A{n}", capabilities, get_behaviour(behaviour), choose, args.trust_dissem_period, args.max_crypto_buf, args.max_trust_buf, args.max_reputation_buf, args.max_stereotype_buf) for (n, behaviour) in enumerate(chain.from_iterable(agent_behaviours)) ] es = get_eviction_strategy(args.eviction_strategy) sim = Simulator(seed, agents, es, args.duration, args.utility_targets, args.log_level) sim.run(args.max_start_delay) sim.metrics.save(sim, args, args.path_prefix)
def test_basic_simulation(self): sim = Simulator(end_time=2) m0 = Message(sim=sim, time=0, priority=9) m1 = Message(sim=sim, time=1, priority=9) m2 = Message(sim=sim, time=1, priority=0) m3 = Message(sim=sim, time=4, priority=9) msgs = [m0, m1, m2, m3] for m in msgs: sim.push(m) sim.do_all_events() self.assertGreaterEqual(sim.time, sim.end_time)
def simulate_benchmark(bench_name, cfg_name, debug=False): benchmark_path = Path(f"{BENCH_ROOT}/{bench_name}").resolve() cfg_path = Path(f"{CFG_ROOT}/{cfg_name}").resolve() simulator = Simulator(benchmark_path, cfg_path, debug) # simulator.only_debug_pu(3) #simulator.run_cycles(51) simulator.run() simulator.print_statistics()
def setUp(self): self.sim = Simulator() self.m0 = Message(self.sim, 1, 'han0', 'cmd') self.m1 = Message(self.sim, 2, 'han1', 'cmd') self.m2 = Message(self.sim, 3, 'han2', 'cmd', preqs=[self.m0, self.m1]) self.adj_list = { self.m0: [self.m2], self.m1: [self.m2], self.m2: [] } self.graph = DirectedGraph() self.graph.from_adjacency_list(self.adj_list) self.seq = Sequence(self.graph)
def setUp(self): self.sim = Simulator() self.agg = MessageAggregator() self.m0 = Message(self.sim, 1, 'han0', 'cmd') self.m1 = Message(self.sim, 2, 'han1', 'cmd') self.m2 = Message(self.sim, 3, 'han2', 'cmd', preqs=[self.m0, self.m1]) self.adj_list = {self.m0: [self.m2], self.m1: [self.m2], self.m2: []} self.graph = DirectedGraph() self.graph.from_adjacency_list(self.adj_list) self.seq = Sequence(self.graph) self.m_alone_pending = Message(self.sim, 4, 'han_alone', 'cmd') self.m_alone_ready = Message(self.sim, 5, 'han_far_away', 'cmd') self.m_alone_ready.state = Message.READY self.m_alone_done = Message(self.sim, 5, 'han_far_away', 'cmd') self.m_alone_done.state = Message.DONE
def setUp(self): self.sim = Simulator() self.agg = MessageAggregator() self.m0 = Message(self.sim, 1, 'han0', 'cmd') self.m1 = Message(self.sim, 2, 'han1', 'cmd') self.m2 = Message(self.sim, 3, 'han2', 'cmd', preqs=[self.m0, self.m1]) adj_list1 = {self.m0: [self.m2], self.m1: [self.m2], self.m2: []} self.seq1 = Sequence(DirectedGraph().from_adjacency_list(adj_list1)) self.m3 = Message(self.sim, 1, 'han0', 'cmd') self.m4 = Message(self.sim, 2, 'han1', 'cmd', preqs=[self.m3]) adj_list2 = {self.m3: [self.m4], self.m4: []} self.seq1 = Sequence(DirectedGraph()) self.seq1.graph.from_adjacency_list(adj_list1) self.seq2 = Sequence(DirectedGraph()) self.seq2.graph.from_adjacency_list(adj_list2)
def __init__(self): print("INITIALISING ENVIRONMENT:") self.width = ConfigReader("width") self.height = ConfigReader("height") self.start_amount_of_hunter = ConfigReader("start_amount_of_hunter") self.start_amount_of_preys = ConfigReader("start_amount_of_prey") print("\tWIDTH: ", int(self.width)) print("\tHEIGHT: ", int(self.height)) print("\tHUNTERS: ", int(self.start_amount_of_hunter)) print("\tPREYS: ", int(self.start_amount_of_preys), "\n") self.prey_model = Preys() self.hunter_model = Hunters() self.prey_model.set_hunters(self.hunter_model) self.simulator = Simulator() self.simulation_time = 0
def main(): args = parse_args() start_time = time.time() total_running_time=0 #Log_handling # Seed the random generator random.seed(args.seed) numpy.random.seed(args.seed) params=SimulatorParams(args.seed,args.no_of_gw,args.no_of_rp,args.duration,args.checkin_interval) for no_of_run in range(args.total_runs): # Create a SimPy environment env = simpy.Environment() # Create a Simulator object, pass the SimPy environment and params objects simulator = Simulator(env, params) # Start the simulation simulator.start() # Run the simpy environment for the specified duration env.run(until=args.duration) # Record endtime and running_time metrics end_time = time.time() if simulator.gw_running_time > simulator.rp_running_time : running_time=simulator.gw_running_time else: running_time=simulator.rp_running_time #Dumping metrics #log.info(simulator.metrics) log.info("SIMULATION CYCLE :%d Total upgrade time :%.2f"%(no_of_run,running_time)) total_running_time +=running_time #Calculating average running time average_running_time=total_running_time / args.total_runs log.info("Average simulation running time for %d runs :(foreach run %d Gateway & %d Repeater) :%.2f"% (args.total_runs,args.no_of_gw,args.no_of_rp,average_running_time))
def _run_accept_experiments(self, beta0_list): separation_ratio = self.separation_ratio if beta0_list is None: raise ValueError( "beta0_list is None, but must contain beta_0 vals.") timer = Timer() name = self.experiment_name for exp in range(self.start_experiments_at, len(beta0_list)): beta0 = beta0_list[exp] noise_list = [beta0, beta0 * separation_ratio] name = self.experiment_name + '_' + str(exp) if self.verbose: print('experiment:', exp + 1, '/', len(beta0_list), ', separation_ratio:', separation_ratio) if self.verbose: print(noise_list) sim = Simulator(self.model, self.learning_rate, noise_list, self.noise_type, batch_size=self.batch_size, n_epochs=self.n_epochs, name=name, n_simulations=self.n_simulations, swap_step=self.swap_step, separation_ratio=separation_ratio, tuning_parameter_name=self.tuning_param_name, surface_view=self.surface_view, burn_in_period=self.burn_in_period, loss_func_name=self.loss_func_name, description=self.description) sim.train_n_times(sim.train_PTLD, train_data=self.data['train_data'], train_labels=self.data['train_labels'], test_data=self.data['test_data'], test_labels=self.data['test_labels'], validation_data=self.data['valid_data'], validation_labels=self.data['valid_labels']) if self.verbose: print() if self.verbose: print('time took:', timer.elapsed_time(), 'min')
def _run_tempfactor_experiments(self): timer = Timer() for exp in range(self.start_experiments_at, self.n_experiments): separation_ratio = self.tuning_parameter_vals[exp] name = self.experiment_name + '_' + str(exp) if self.verbose: print('experiment:', exp + 1, '/', self.n_experiments, ', param_val:', separation_ratio) if self.verbose: print(name) noise_list = [ self.beta_0 * separation_ratio**i for i in range(self.n_replicas) ] if self.verbose: print(noise_list) sim = Simulator(self.model, self.learning_rate, noise_list, self.noise_type, batch_size=self.batch_size, n_epochs=self.n_epochs, name=name, n_simulations=self.n_simulations, swap_step=self.swap_step, separation_ratio=separation_ratio, surface_view=self.surface_view, burn_in_period=self.burn_in_period, loss_func_name=self.loss_func_name, description=self.description) sim.train_n_times(sim.train_PTLD, train_data=self.data['train_data'], train_labels=self.data['train_labels'], test_data=self.data['test_data'], test_labels=self.data['test_labels'], validation_data=self.data['valid_data'], validation_labels=self.data['valid_labels']) if self.verbose: print() if self.verbose: print('time took:', timer.elapsed_time(), 'min')
def __init__(self): self.action_space = spaces.Box( np.array([0, 1, 2, 3, 4, 5]), np.array([355, 356, 357, 358, 359, 360])) # self.observation_space = spaces.Dict({ # 'capacity_matrix': spaces.Box(low=0, high=10, shape=(4, 4, 1), dtype=np.int32), # 'distance_matrix': spaces.Box(low=0, high=10000, shape=(4, 4, 1), dtype=np.int32), # 'time_tables': spaces.Box(low=0, high=1440, shape=(3, 6, 1), dtype=np.int32), # # 'max_passengers_per_h': spaces.Discrete(500) # }) self.observation_space = spaces.Box(low=0.0, high=1.0, shape=(4 * 4 + 4 * 4 + 3 * 6 + 1, ), dtype=np.float64) self.state_0 = RL_Network() self.timetables = copy.deepcopy(self.state_0.TIME_TABLES) self.current_schedule_pointer = 0 self._reward = 0 self._simulator = Simulator(DemoNetwork1)
def run_simulator(self, team1_names, team2_names, num_sims, attack_heuristic='Random', heal_heuristic='LowestHealth'): self.num_sims = num_sims self.res.num_sims = num_sims heuristics = heuristic_container.HeuristicContainer( attack_selection=heuristic_mapping[attack_heuristic](), heal_selection=heuristic_mapping[heal_heuristic]()) # Add the name prefix so that combatants with the same name on # either side can be differentiated team1 = [ Combatant.load_combatant( name, name_suffix="t1_{}".format(i), should_ready=True, num_enemies=len(team2_names)) for i, name in enumerate(team1_names)] team2 = [ Combatant.load_combatant( name, name_suffix="t2_{}".format(i), should_ready=True, num_enemies=len(team1_names)) for i, name in enumerate(team2_names)] self.res.number_of_rounds = [] self.res.number_of_player_deaths = [] self.res.winning_teams = [] for i in range(self.num_sims): sim = Simulator(team1, team2) num_rounds, num_player_deaths, winning_team = sim.run_battle( heuristics) self.res.number_of_player_deaths.append(num_player_deaths) self.res.winning_teams.append(winning_team) self.res.number_of_rounds.append(num_rounds) self.save_simulation(team1, team2)
def _create_simulation(self): sg = SimulationGraph(self.nodes, 1) self.simulator = Simulator(sg)
from simulation.simulator import Simulator s = Simulator(from_date='2014-01-01', to_date='2015-01-01', starting_fiat=0, starting_coins=1, ema1=8, ema2=13, display_orders=False)