def test_D_shelf_capacity_and_overflow(self): log(type(self).__name__ + '.test_D_shelf_capacity_and_overflow()') import sim reload(sim) def gen_orders(temp, qty): return [ gen_unique_order(shelf_life=100, decay_rate=0, temp=temp) for i in range(qty) ] # because 10-10-10-15: should_ideal = gen_orders('hot', 10) should_ideal.extend(gen_orders('cold', 10)) should_ideal.extend(gen_orders('frozen', 10)) should_overflow = gen_orders('hot', 5) should_overflow.extend(gen_orders('cold', 5)) should_overflow.extend(gen_orders('frozen', 5)) os = list(should_ideal) os.extend(should_overflow) sim.configure('configs/config-%s-2-2-6-10-10-10-15-orders.py' % self.concurrency) sim.cfg['orders_literal'] = os #for o in sim.cfg['orders_literal']: log(o) sim.cfg['courier_dispatch_enabled'] = False sim.run() # do all the shelves have the capacity we expect? self.assertEqual(sim.cfg['shelf_capacity']['hot'], 10) self.assertEqual(sim.cfg['shelf_capacity']['cold'], 10) self.assertEqual(sim.cfg['shelf_capacity']['frozen'], 10) self.assertEqual(sim.cfg['shelf_capacity']['overflow'], 15) # is every shelf full? for sn in sim.kt.shelf_names: #log('shelf capacity reached for shelf?: %s' % sn) self.assertEqual(len(sim.kt.shelves[sn]), sim.cfg['shelf_capacity'][sn]) # check that every order we think should be on the overflow shelf is actually there: for o in should_overflow: #log('order: %s' % str(o)) oid = o['id'] self.assertTrue( oid in sim.kt.order_ready) # its ready for pickup and has a timestamp self.assertTrue( oid in sim.kt.order_locs ) # we know it's location (what shelf, or capdrop or wasted) loc = sim.kt.order_locs[oid] #log('loc: %s' % loc) self.assertTrue( loc in sim.kt.shelf_names ) # its location is a shelf (single temp or overflow) self.assertEqual(loc, 'overflow') # its reported location is overflow self.assertTrue( o in sim.kt.shelves[loc]) # its on the shelf the sim said
def test_H_courier_arrival(self): log(type(self).__name__ + '.test_H_courier_arrival()') perms = ('2-2-6-10-10-10-15-orders', '2-2-2-10-10-10-15-orders', '2-0-0-10-10-10-15-orders', 'inf-2-6-10-10-10-15-orders') log('will be %i perms: %s' % (len(perms), perms)) for pi, p in enumerate(perms, 1): configmod = 'configs/config-%s-%s.py' % (self.concurrency, p) log(' perm %i of %i: %s' % (pi, len(perms), configmod)) import sim reload(sim) sim.configure(configmod) orders = [ gen_unique_order(shelf_life=100, decay_rate=0) for i in range(10) ] sim.cfg['orders_literal'] = orders sim.run() for oi, o in enumerate(orders, 1): oid = o['id'] log(' testing order %i of %i: %s' % (oi, len(orders), oid)) self.assertTrue(oid in sim.kt.order_ready) self.assertTrue(oid in sim.kt.courier_arrivals) r = sim.kt.order_ready[oid] a = sim.kt.courier_arrivals[oid] self.assertGreaterEqual(a, r + sim.cfg['courier_arrival_min']) if self.concurrency != 'T': self.assertLessEqual(a, r + sim.cfg['courier_arrival_max'])
def main(): for sample in np.arange(-5,90.1,0.5): work = 'work_%s' % sample if os.path.exists(os.path.join(work, 'arcs-sim-wEidata.nxs')): print "skipping %s" % sample continue run(sample) return
def main(): for sample in np.arange(-5,90.1,0.5): work = 'work_%s' % sample if os.path.exists(os.path.join(work, 'arcs-sim-wEidata.nxs')): # if os.path.exists(os.path.join(work, 'log.scatter')): # this is used when sometimes the job got put into hold, and it is not running by the queueing system. in that case, the jobs that are on hold need to be killed, and then we can rerun this script to resubmit the jobs print "skipping %s" % sample continue run(sample) return
def test_G_waste(self): log(type(self).__name__ + '.test_G_waste()') import sim reload(sim) os = [ gen_unique_order( shelf_life=100, decay_rate=0), # will never waste away. will be delivered gen_unique_order( shelf_life=100, decay_rate=300 ), # discovered as waste prior to its courier arriving gen_unique_order( shelf_life=100, decay_rate=300 ), # discovered as waste prior to its courier arriving gen_unique_order(shelf_life=100, decay_rate=300) ] # discovered as waste by its courier upon arrival # only the last 3 of the 4 should waste away should_deliver = (os[0], ) should_waste = (os[1], os[2], os[3]) configmod = 'configs/config-%s-0.5-3-3-10-10-10-15-orders.py' % self.concurrency sim.configure(configmod) sim.cfg['orders_literal'] = os sim.run() self.assertEqual(sim.kt.counts['event:order_received'], len(os)) # 4 for o in os: ov = sim.kt.order_value(o, sim.kt.now) log('o: %s, %f' % (str(o), ov)) for o in should_waste: ov = sim.kt.order_value(o, sim.kt.now) log('sw: %s, %f' % (str(o), ov)) self.assertTrue(o in sim.kt.wasted) for o in sim.kt.wasted: ov = sim.kt.order_value(o, sim.kt.now) log('w: %s, %s' % (str(o), str(ov))) self.assertTrue(o in should_waste) oid = o['id'] self.assertEqual(sim.kt.order_locs[oid], 'wasted') self.assertEqual(len(sim.kt.wasted), len(should_waste)) # 3 self.assertEqual(sim.kt.counts['ordercheck_wasted'], 2) self.assertEqual(sim.kt.counts['pickupfail_wasted_prior'], 2) self.assertEqual(sim.kt.counts['pickupfail_wasted_now'], 1) for i in range(len(should_waste) ): # check if they wasted in the order we expected self.assertEqual(should_waste[i], sim.kt.wasted[i]) self.assertEqual(sim.kt.counts['orders_delivered'], len(should_deliver)) # 1
def competeSeeds(self,list_seeds): """Competes each seeding against each other. input: list of list of seeds Returns best seed and score. Uses provided simulator.""" scoring=[20,15,12,9,6,4,2,1,0] #warning! if len(list_seeds)<self.numPlayers: print "Number of seeds is smaller than number of players! Adding random." for i in range(self.numPlayers-len(list_seeds)): list_seeds.append(list(np.random.randint(len(self.adj),size=self.numSeeds))) labels=map(str,range(len(list_seeds))) #since only care about being unique scores=[0]*len(list_seeds) dict_seeds=dict(itertools.izip(labels,list_seeds)) #competes seeds in tournament style base on size of graph matches=itertools.combinations(dict_seeds.iteritems(),self.numPlayers) for match in matches: results=sim.run(self.adj,dict(match))[1] #print results #sort by number of seeds sorted_results=sorted(results,key=results.get,reverse=True) #print results #increment scores for i in range(len(sorted_results)): scores[int(sorted_results[i])]+=scoring[i] #print list_seeds #print scores return list_seeds[np.argmax(scores)]
def volume_sweep(events: int, num_atoms: int, energy: float, mass: float, radius: float, data_points: int, dpath: str = '..') -> None: """Call sim.run() across a range of volumes and output the resulting data as a csv.""" part_vol: float = radius**(3) * np.pi * 4 / 3 print(part_vol) start_vol: float = 4 * num_atoms * part_vol print(start_vol) end_vol: float = 10**10 * start_vol print(end_vol) vols: np.ndarray = np.logspace(math.log10(start_vol), math.log10(end_vol), data_points) print(vols) data: List[Tuple[float, float, float]] = [] for vol in vols: point: Tuple[float, float, float] = sim.run(events, num_atoms, vol, energy, mass, radius) data.append(point) df: pd.DataFrame = pd.DataFrame(data=data, columns=["Pressure", "Volume", "Nkt"]) df.to_csv(f"{dpath}/vsweep.csv")
def tactics_fewer(adj_list, outfile, n_seeds, n_players): G = parse_graph(adj_list) degrees = G.degree() top_degree = [ k[0] for k in sorted(degrees, key=lambda t: t[1], reverse=True) ] TA_set = top_degree[:n_seeds - 2] neighbors_of_top_dog = G[TA_set[0]] # nbrs = [k[0] for k in sorted(G.degree(G[TA_set[0]]), key=lambda t: t[1], reverse=True) if k[0] not in seeds and k[0] not in TA_set] # seeds.append(nbrs[0]) seeds = set(TA_set) nbrs = [ k[0] for k in sorted( G.degree(G[TA_set[0]]), key=lambda t: t[1], reverse=True) ] i = 0 while len(seeds) < n_seeds: seeds.add(nbrs[i]) i += 1 seeds = list(seeds) print(sim.run(adj_list, {'us': seeds, 'them': TA_set})) print_to_file(seeds * 50, outfile)
def make_simulation(filename, N): """ Run a simulation with 2 or more strategies for the given input graph """ graph = jsonToDict(filename) print("{} total nodes.".format(len(graph))) ########### run a strategy here # use half of degree centrality # topN_1 = degreeCentrality(graph, N) # topN_2 = closenessCentrality(graph, N) # # topN = topN_1[5:] # i = 9 # while len(topN) < 10: # topN.append(topN_2[i]) # i -= 1 # topN_2 = topN topN_1 = degreeCentrality(graph, N) if len(graph) > 2500: topN_2 = voteRank(graph, N) # less accurate, but shorter runtime else: topN_2 = closenessCentrality(graph, N) # more accurate ########### # simulate listOfStrategies = {"Degree": topN_1, "Hybrid": topN_2} results = sim.run(graph, listOfStrategies) print(results)
def run_simulations(strategies_dict, num_seeds, graph): ''' Runs 50 iterations of sim.py using specified strategies. Outputs the results of each run and also the final count of how many times each strategy took the most number of nodes in an iteration/run. Args: strategies_dict -- dict of strategy(key) to list of seed_nodes(value) over all 50 runs num_seeds -- the number of seeds/nodes to pick per run graph -- the input graph Returns: n/a ''' nodes = dict() results_dict = defaultdict(int) # Stores how many times this strategy won out for i in range(50): start = i * num_seeds end = start + num_seeds for s in strategies_dict: # s should only be r, b, or d nodes[s] = strategies_dict[s][start:end] # run simulation for each iteration results = sim.run(graph, nodes) print(results) best_strategy = max(results.iteritems(), key=operator.itemgetter(1))[0] results_dict[best_strategy] += 1 print print("----------------------- OVERALL RESULTS -----------------------") print(results_dict)
def tactics_1st_gen(adj_list, outfile, n_seeds, n_players): N = 100 G = parse_graph(adj_list) centrality = nx.eigenvector_centrality(G) central_nodes = [ k for k in sorted(centrality, key=centrality.get, reverse=True) ] print('most central: {}'.format(','.join( [central_nodes[i] for i in range(10)]))) clustering = nx.clustering(G, central_nodes[:N]) cluster_nodes = [ k for k in sorted(clustering, key=clustering.get, reverse=True) ] print('highest clustering coefficient: {}'.format(','.join( [cluster_nodes[i] for i in range(10)]))) best_boys = [(n, centrality[n] * clustering[n]) for n in central_nodes[:N]] best_boys = sorted(best_boys, key=lambda t: t[1], reverse=True) final_selections = [] for i in range(50): selections = dict((str(i), selector(G, n_seeds, best_boys[i:])) for i in range(n_players)) simulation = sim.run(adj_list, selections) best = [ k for k in sorted(simulation, key=simulation.get, reverse=True) ][0] final_selections.extend(selections[best]) print_to_file(final_selections, outfile)
def replay(graph, filename, list_of_nodes): strategies = json.load(open(filename)) Ranks = 0 for i in range(50): print('***** Round ' + str(i) + ' *****') # print(list_of_nodes) strategy = defaultdict(list) for key in strategies: strategy[key] = strategies[key][i] strategy['Kaigoo'] = list_of_nodes[i] results = sim.run(graph, strategy) print(results) scores = [] for key in results: scores.append(results[key]) scores = sorted(scores) score = results['Kaigoo'] for i in range(num_player): if scores[i] == score: rank = num_player - i print('Rank: ' + str(rank)) Ranks = Ranks + rank print('Final Rank: ' + str(Ranks / 50))
def do_large_order_counts_run(total): log('do_large_order_counts_run(): %i orders' % total) import sim reload(sim) sim.configure(configmod) sim.cfg['orders_literal'] = [ gen_unique_order(100, 25, temp) for i in range(total) ] sim.cfg[ 'log_config_large_orders_literal'] = False # don't spam the log with a huge dump of orders_literal cfg sim.run() self.assertEqual(sim.kt.peaks['overflow'], 0) if self.concurrency == 'T': self.assertRange(sim.kt.peaks[temp], 4, 5) #TODO else: # priority self.assertEqual(sim.kt.peaks[temp], 4) self.assertEqual(sim.kt.counts['orders_delivered'], len(sim.cfg['orders_literal']))
def test_C_order_added_to_temp_shelf(self): log(type(self).__name__ + '.test_C_order_added_to_temp_shelf()') self.assertTrue(True) import sim reload(sim) sim.configure('configs/config-%s-inf-2-6-10-10-10-15-orders.py' % self.concurrency) sim.cfg['orders_literal'] = [ gen_unique_order(temp=t) for t in sim.SINGLE_TEMPS ] sim.cfg['courier_dispatch_enabled'] = False sim.run() for o in sim.cfg['orders_literal']: #log('order: %s' % str(o)) oid = o['id'] self.assertTrue( oid in sim.kt.order_ready) # its ready for pickup and has a timestamp self.assertTrue( oid in sim.kt.order_locs ) # we know it's location (what shelf, or capdrop or wasted) loc = sim.kt.order_locs[oid] #log('loc: %s' % loc) self.assertTrue( loc in sim.kt.shelf_names ) # its location is a shelf (single temp or overflow) self.assertEqual(loc, o['temp']) # its the ideal shelf for its temp self.assertTrue( o in sim.kt.shelves[loc]) # its on the shelf the sim said ov = sim.kt.order_value(o, sim.kt.now) #log('oval: %f' % ov) if self.concurrency == 'T': self.assertRange( ov, 0.998, 1.0 ) # cuz in temporal mode has been observed after sim end as low as 0.9988274574279785 else: # priority self.assertEqual( ov, 1.0 ) # order value is max/ideal, since fresh cuz no time passed since ready
def main(): protocol = argv[1] N = int(argv[2]) p = float(argv[3]) R = int(argv[4]) T = int(argv[5]) seeds = [int(arg) for arg in argv[6:]] stations = run(protocol, N, p, R, T, seeds) out = open('results/' + protocol + '_asn2_results.txt', 'a') output(out, stations, protocol, N, p, R, T) out.close()
def test_E_capacity_drops(self): log(type(self).__name__ + '.test_E_capacity_drops()') import sim reload(sim) configmod = 'configs/config-%s-2-2-6-1-1-0-0-orders.py' % self.concurrency os = [ gen_unique_order(shelf_life=100, decay_rate=0, temp='hot') for i in range(2) ] os.extend([ gen_unique_order(shelf_life=100, decay_rate=0, temp='cold') for i in range(2) ]) os.append(gen_unique_order(shelf_life=100, decay_rate=0, temp='frozen')) # we have 1 more hot order than will fit on the kitchen's hot shelf. likewise for cold. # no frozen capacity at all. and NO overflow capacity # therefore, we'd expect that the sim will capdrop the 2nd hot order, 2nd cold, and the sole frozen order: should_drop = ( os[1], os[3], os[4] ) # the 3 of the 5 orders we expect to see in the capdrop state sim.configure(configmod) sim.cfg['orders_literal'] = os sim.cfg['courier_dispatch_enabled'] = False sim.run() self.assertEqual(len(sim.kt.capacity_dropped), 3) # we expect to see a total of 3 capdropped orders for o in should_drop: #log('capdrop eval: %s' % str(o)) oid = o['id'] self.assertTrue(oid in sim.kt.order_ready) self.assertTrue(oid in sim.kt.order_locs) loc = sim.kt.order_locs[oid] self.assertEqual(loc, 'capdrop') self.assertTrue(o in sim.kt.capacity_dropped)
def select_best_discounts(G, n, num_players, max_iter=1000): ''' Choose the best group of nodes based on simulations against a strategy that picks the best n out of the top 1-2n (random) degree or eigenvector centralities. After random walking, it returns the 50 best groups of nodes. ''' round_score = {} # key is round number, value is round_seed = {} # key is round number, value is seed list neighbor_c = neighbor_centrality(G) degree_c = nx.degree_centrality(G) eigen_c = nx.eigenvector_centrality(G) discounters = [discount_neighbor, discount_degree] graph_dict = make_dict_from_graph(G) ta_possible_degree_nodes = list(G.nodes()) ta_possible_eigen_nodes = list(G.nodes()) ta_possible_degree_nodes.sort(reverse=True, key=lambda v: degree_c[v]) ta_possible_eigen_nodes.sort(reverse=True, key=lambda v: eigen_c[v]) node_lists = {} # pass into sim for i in range(max_iter): print('\rround {}/{}'.format(i, 1000), end='') # generate our nodes seeds = seed_by_discount(G, n, num_players, discounters, [neighbor_c, degree_c]) node_lists['pandemonium'] = seeds # test it 5 times against random ta nodes # build ta nodes; score is how many total nodes it won score = 0 for _ in range(3): for dummy_player in range(num_players): ta_nodes = random.choice( [ta_possible_eigen_nodes, ta_possible_degree_nodes]) rand_scaling_factor = random.uniform(1, 2) ta_nodes = random.sample( ta_nodes[:math.ceil(rand_scaling_factor * n)], n) node_lists['TA{}'.format(dummy_player)] = ta_nodes results = sim.run(graph_dict, node_lists) score += results['pandemonium'] round_score[i] = score round_seed[i] = seeds # find best 50 scores by node indices = list(round_score.keys()) indices.sort(reverse=True, key=lambda i: round_score[i]) final_seeds = [] for k in range(50): final_seeds.append(round_seed[indices[k]]) return final_seeds
def tactics_degree(adj_list, outfile, n_seeds, n_players): G = parse_graph(adj_list) degrees = G.degree() top_degree = [ k[0] for k in sorted(degrees, key=lambda t: t[1], reverse=True) ] TA_set = top_degree[:n_seeds] neighbors_of_top_dog = G[TA_set[0]] top_neighbors = [t for t in TA_set if t in neighbors_of_top_dog] seeds = TA_set[:n_seeds - 1] TA_set = top_degree[:n_seeds] best = 0 final_seeds = [] for n in G[TA_set[0]]: simulation = sim.run(adj_list, {'us': seeds + [n], 'them': TA_set}) if simulation['us'] > best: print('{} -> {}'.format(best, simulation['us'])) best = simulation['us'] final_seeds = seeds + [n] print(sim.run(adj_list, {'us': final_seeds, 'them': TA_set})) print_to_file(final_seeds * 50, sys.argv[2])
def step(self): self.t += 1 mu_bar = np.empty(self.node_count) for i in range(self.node_count): mu_bar[i] = np.maximum( self.mu[i] + np.sqrt(3 * np.log(self.t) / (2 * self.T[i])), 2) ind = np.argpartition(mu_bar, -self.k)[-self.k:] sim_data = { 'self': [str(x) for x in ind], 'alt': [str(x) for x in self.alt_picks], } results = sim.run(self.adj_list, sim_data) score = results['self'] / self.node_count self.T[ind] += 1 self.mu[ind] = self.mu[ind] + (score - self.mu[ind]) / self.T[ind] return ind
def play(game, playerlist): assert game.num_players == len(playerlist) graph = nx.to_dict_of_lists(game.network) nodes = {} for i, player in enumerate(playerlist): nodes["strategy" + str(i)] = player.give_output_list(game) assert len(nodes["strategy" + str(i)]) == game.num_seeds #print nodes["strategy" + str(i)] #print result = sim.run(graph, nodes) return result
def thompson(self): self.t += 1 theta = np.zeros(self.node_count) for i in range(self.node_count): alpha = ALPHA_0 + self.mu[i] beta = BETA_0 + self.T[i] - self.mu[i] theta[i] = np.random.beta(alpha, beta) ind = np.argpartition(theta, -self.k)[-self.k:] sim_data = { 'self': [str(x) for x in ind], 'alt': [str(x) for x in self.alt_picks], } results = sim.run(self.adj_list, sim_data) score = results['self'] / self.node_count self.T[ind] += 1 self.mu[ind] += score return ind
def test_run(): cases = ["teleop", "shared", "active=1", "active=20", "active=100"] for case in cases: ics = sim.load("./.test_examples/" + case + ".json") want = np.load("./.test_examples/" + case + ".npy") try: got = sim.run(ics) except Exception as e: print("sim_test.test_run: while running " + repr(case) + " got exception: " + repr(e)) traceback.print_exc() break # f, (a1, a2) = plt.subplots(2) # duo.visualize(a1, got["conditions"]["start"], got["conditions"]["goals"], trajectories=[got["trajectory"]], u_hs=[got["u_h"]]) # duo.visualize(a2, got["conditions"]["start"], got["conditions"]["goals"], trajectories=[want[0]], u_hs=[want[2]]) # plt.show() got = (got["trajectory"], got["beliefs"], got["u_h"], got["u_r"]) try: if not (len(want) == 4 and len(got) == 4): raise Exception("test_run expect len(got) = len(want) = 4") if (len(got[0]) != len(want[0])): raise Exception("trajectory lengths don't match: got: " + repr(len(got[0])) + " want: " + repr(len(want[0]))) if not np.allclose(want[0], got[0]): print(want[0]) print(got[0]) raise Exception("trajectory isn't matching") if not np.allclose(want[1], got[1]): raise Exception("belief isn't matching") if not np.allclose(want[2], got[2]): raise Exception("u_h isn't matching") if not np.allclose(want[3], got[3]): raise Exception("u_r isn't matching") except Exception as e: print("sim_test.test_run: while running " + repr(case) + ", " + repr(e))
def simulateSeeds(self, dict_seeds, plot=False): """Competes each seeding against each other. dict_seeds: key=name, value=list of seeds graph: adjacency dictionary Returns seed results. Uses provided simulator.""" #if len(dict_seeds)!=self.numPlayers: #raise AssertionError("Invalid Input! Not enough player seeds.") mapping, results = sim.run(self.adj, dict_seeds) if plot: self.drawGraph(mapping, dict_seeds.keys()) #check #if sum(results.values())!=len(self.adj): # print "Warning: Mismatching number of nodes in results." return results
def simulateSeeds(self,dict_seeds,plot=False): """Competes each seeding against each other. dict_seeds: key=name, value=list of seeds graph: adjacency dictionary Returns seed results. Uses provided simulator.""" #if len(dict_seeds)!=self.numPlayers: #raise AssertionError("Invalid Input! Not enough player seeds.") mapping,results=sim.run(self.adj,dict_seeds) if plot: self.drawGraph(mapping,dict_seeds.keys()) #check #if sum(results.values())!=len(self.adj): # print "Warning: Mismatching number of nodes in results." return results
def seeds_by_degree_cheese(G, G_json, num_cheese, total_seeds): ''' Number of cheese nodes for destroying the TA_degree strategy Recommended to not use too many nodes (keep num_cheese as close to max) because runtime scales by choose function. @param G: graph @param num_cheese: number of nodes that we are cheesing @return nodes that win the best against TA_degree ''' free = total_seeds - num_cheese graph_degrees = degree_centrality(G) graph_degrees_list = [(node, graph_degrees[node]) for node in graph_degrees] graph_degrees_list.sort(reverse=True, key=lambda x: x[1]) seeds = [ graph_degrees_list[i][0] for i in range(min(num_cheese, total_seeds)) ] win_by = 0 sim_results = {} successful_seeds = [] ta_seeds = [ graph_degrees_list[total_seeds - i - 1][0] for i in range(max(free, 0)) ] combos = list(itertools.combinations(graph_degrees_list[num_cheese:], free)) combos_length = len(combos) iteration = 0 for combo in combos: print('\r combo {}/{}'.format(iteration, combos_length), end='') combo_nodes = tuple([node[0] for node in combo]) strat = {'ta': ta_seeds, 'pandemonium': combo_nodes} sim_result = sim.run(G_json, strat) sim_results[combo_nodes] = sim_result if sim_result['pandemonium'] - sim_result['ta'] > win_by: win_by = sim_result['pandemonium'] - sim_result['ta'] successful_seeds = combo_nodes iteration += 1 print('Best win: ', win_by) return seeds + list(successful_seeds)
def give_output_list(self, game): """ This returns a list of the selected nodes. The twin attack player finds the highest degree nodes, and for each, it selects two neighbors of that node and""" # First, find out what the TA is doing. if game in self.game_memo_dict: return self.game_memo_dict[game] nodes = nx.nodes(game.network) value_dict = nx.degree_centrality(game.network) nodes.sort(key=lambda x : value_dict[x], reverse=True) ta_output_list = nodes[:game.num_seeds] candidate_nodes = nodes[:25] i = 0 while i < 10000000: i += 1 selections = set() while len(selections) < game.num_seeds: selections.add(random.choice(candidate_nodes)) selections = list(selections) result = sim.run(nx.to_dict_of_lists(game.network), {"s0" : ta_output_list, "s1" : selections}) if result["s0"] < result["s1"]: break assert len(selections) == game.num_seeds self.game_memo_dict[game] = selections return list(selections)
def temp_sweep(events: int, num_atoms: int, volume: float, mass: float, radius: float, data_points: int, dpath: str = '..') -> None: """Call sim.run() across a range of temperatures and save the results as a CSV.""" start_energy: float = num_atoms * mass end_energy = 1e6 * start_energy es: np.ndarray = np.linspace(start_energy, end_energy, num=data_points) data: List[Tuple[float, float, float]] = [] for e in es: point: Tuple[float, float, float] = sim.run(events, num_atoms, volume, e, mass, radius) data.append(point) df = pd.DataFrame(data, columns=['Pressure', 'Volume', 'NkT']) df.to_csv(f"{dpath}/tsweep.csv")
def test_params(n): w = (n % (20 ** 4)) / (20 ** 3) x = (n % (20 ** 3)) / (20 ** 2) y = (n % (20 ** 2)) / (20 ** 1) z = (n % (20 ** 1)) / (20 ** 0) successes = 0 answers = [] for g in range(len(jsonfiles)): nodes = {} (num_players, num_seeds, data, G) = scanfile('2.10.' + jsonfiles[g] + '.json') seeds = __import__('cdn').generate_seeds(num_players, num_seeds, G,w,x,y,z) seeds = map(str, list(seeds))[:num_seeds] nodes['cdn'] = seeds seeds = __import__('degree').generate_seeds(num_players, num_seeds, G) seeds = map(str, list(seeds))[:num_seeds] nodes['degree'] = seeds answers.append(sim.run(data,nodes)) if(answers[len(answers) - 1]['cdn'] > answers[len(answers) - 1]['degree']): successes = successes + 1 if(successes > len(jsonfiles) - 2): print 'successes:', successes, 'params:',w,x,y,z for h in range(len(jsonfiles)): print answers[h]
for i in range(num_nodes): for j in range(i, num_nodes): if i == j: dist[i][j] = 0 elif str(i) in graph[str(j)]: dist[i][j] = 1 dist[j][i] = 1 # Use floyd-warshall algorithm to calculate the diameters for k in range(num_nodes): for i in range(num_nodes): for j in range(num_nodes): if dist[i][k] + dist[k][j] < dist[i][j]: dist[i][j] = dist[i][k] + dist[k][j] sum_d = 0 dist_centrality = [] for i in range(num_nodes): for j in range(num_nodes): if i != j and dist[i][j] == 1000: continue sum_d += dist[i][j] dist_centrality.append([i, float(sum_d) / (num_nodes - 1)]) sum_d = 0 # Print the idea number of nodes this strategy can capture for i in range(10): deg_seed = get_top_seeds(deg_centrality) dist_seed = get_top_seeds(dist_centrality) print sim.run(graph, {"Degree":deg_seed, "Distance":dist_seed})
import sys import json import random import sim from operator import itemgetter if __name__ == "__main__": filename = sys.argv[1] graph = json.loads(open(filename).read()) num_players = int(filename.split('.')[0]) num_seeds = int(filename.split('.')[1]) # Calculate centrality centrality = [] v = len(graph) for i in range(v): centrality.append([i, len(graph[str(i)])]) c_sorted = sorted(centrality, key=itemgetter(1), reverse=True) seeds_deg = [str(c_sorted[i][0]) for i in range(num_seeds)] seeds_cheat = [str(c_sorted[i][0]) for i in range(num_seeds+2)] random.shuffle(seeds_cheat) seeds_cheat = seeds_cheat[:num_seeds] print sim.run(graph, {"deg":seeds_deg, "cheat":seeds_cheat}) f = open(filename[:-4] + 'sol', 'w') for s in seeds_cheat: f.write(str(s) + '\n') f.close()
else: with open(dir + '/' + fname, 'r') as f: print('loading %s into %s' %(fname, fname[:2])) data[fname[:2]] = json.load(f) iter = 0 print("iterations: " + str(len(data['p1']))) for key1, val1 in tqdm(data['p1'].iteritems()): for key2, val2 in data['p2'].iteritems(): d = {'p1': [str(x) for x in val1], 'p2': [str(x) for x in val2]} temp = scores.get(key1,{}) temp[key2] = temp.get(key2, 0) + sim.run(adj_list, d)['p1'] scores[key1] = temp temp = wins.get(key1, {}) temp[key2] = int(scores[key1][key2] > 250) wins[key1] = temp with open(dir + '/' + 'costMatrix', 'w') as f: json.dump(scores, f) with open(dir + '/' + 'winMatrix', 'w') as f: json.dump(wins, f) keys1 = sorted(scores.keys())
for i in range(v): centrality.append([i, len(graph[str(i)])]) c_sorted = sorted(centrality, key=itemgetter(1), reverse=True) dic = {} for i in range(num_players - 1): dic["deg" + str(i)] = rand_degree(centrality, num_seeds, num_players) # Randomly choose a number of seeds from the topList and output to file seeds_start = (num_players * num_seeds) / competition_factor + 1 seeds = [] while len(seeds) < num_seeds: seeds_end = seeds_start + int(stair_width * num_seeds) stair = [str(c_sorted[i][0]) for i in range(seeds_start, seeds_end)] random.shuffle(stair) seeds += stair[:(num_seeds / safety_coefficient)] seeds_start = seeds_end dic["many"] = seeds # Print the idea number of nodes this strategy can capture print sim.run(graph, dic) print (len(graph)) f = open(filename[:-4] + 'sol', 'w') for s in seeds: f.write(str(s) + '\n') f.close()
common.append([j, len(set(graph[i]) & set(graph[str(j)]))]) common.sort(key=itemgetter(1), reverse=True) for c in common: k = str(c[0]) if k not in seeds_deg_supp: seeds_deg_supp.append(k) break # seeds_deg_supp.extend(seeds_deg_2[:num_seeds_supp]) # print(seeds_deg_supp) # print(seeds_highest_deg) # Print the idea number of nodes this strategy can capture print sim.run(graph, {"many":seeds, "deg":seeds_deg}) print sim.run(graph, {"deg":seeds_deg, "two":seeds_deg_supp}) # print(seeds_deg_supp) if num_players == 2: seeds = seeds_deg_supp f = open(filename[:-4] + 'sol', 'w') for s in seeds: f.write(str(s) + '\n') f.close()
import sim from load_graph import load_graph from select_best_neighbors import select_best_neighbors from select_degree import select_degree graph_name = 'testgraph2.json' graph = load_graph(graph_name) num_seeds = 10 strategies = {} strategies['player1'] = select_best_neighbors(graph, num_seeds) strategies['player2'] = select_degree(graph, num_seeds) results = sim.run(graph, strategies) for player, winnings in sorted(results.items()): print(str(player) + " got " + str(winnings) + " nodes")
strats = sys.argv[2:] # This simulation is supposed to simulate people playing against each other. # So, we want there to be strategies for each person. if num_players != len(strats): print "Usage: python runSim.py graph_filename.json strat1 strat2 ..." sys.exit() # This simulation is here to simulate people playing against each other. d = {} for i in range(num_players): # Each player will invoke a call to the their particular strategy. subprocess.call(["python", strats[i], sys.argv[1], "1"]) # The dictionary will then store as a key value: # key = [STRATEGY_NAME][PLAYERID] # where the STRATEGY_NAME is the python file (without the .py), and the # PLAYERID is the integer that corresponds to the particular player. # The value stored in this dictionary will be the particular output for this # particular strategy. This output is the adjacency list. d['%s%d' %(str(strats[i][:-3]), i)] = [line.rstrip('\n') for line in open('output.txt')] with open(sys.argv[1]) as data_file: data = json.load(data_file) print sim.run(data,d)
output_file.close() print('Wrote output to `{0}`!'.format(output)) print('Preparing benchmark strategy and running simulation...') benchmark_seeds = benchmark_strategy.run(graph, int(seed_node_count), adj_list=graph_data) winner_count = defaultdict(int) for i in range(0, 0): print("Run #", i) simd = json.load(open('graphs/27.10.2-RabidPandas.json')) simd2 = {k: v[i] for k, v in simd.items() if k != 'RabidPandas'} simd2['RabidPandas'] = seed_node_list sim_data = { benchmark_strategy.name + ' (benchmark)': [str(x) for x in benchmark_seeds], strategy.name: [str(x) for x in seed_node_list], } results = sim.run(graph_data, simd2, verbose=0, visualize=visualize) print('Results:') for strategy_name, node_count in results.items(): print(' {0: <4} -> {1}'.format(node_count, strategy_name)) import operator winner = max(results.items(), key=operator.itemgetter(1))[0] winner_count[winner] += 1 print('Results:') for strategy_name, node_count in winner_count.items(): print(' {0: <4} -> {1}'.format(node_count, strategy_name))
# Format seed nodes in proper format for simulation strategies = format_nodes(results, trial) #print strategies # print len(strategies) # for elem in strategies: # print "NEW DICT" # print elem # nodes = {} # count = 0 # nodes[str(count)] = strategies[count][str(0)] # count += 1 # nodes[str(count)] = strategies[count][str(0)] # count += 1 # nodes[str(count)] = strategies[count][str(0)] # count += 1 # nodes[str(count)] = strategies[count][str(0)] # count += 1 # nodes[str(count)] = strategies[count][str(0)] # print "Nodes are: ", nodes # print # sim.run(graph, nodes) # Run simulation to compare scores of various strategies for i in range(50): nodes = {} for j in range(int(num_players) + 1): nodes[str(j)] = strategies[j][str(i)] sim.run(graph, nodes)
if player != 'pandemonium': # don't add our own seeds from the round player_values[player] = player_seeds[player][round] # read our seeds: every num_seeds lines are the seeds for our round player_values['pandemonium'] = our_seeds[round] # check which of our seeds are boomed boomed_seeds = [] surviving_seeds = num_seeds for seed in player_values['pandemonium']: for key in player_values: if key != 'pandemonium': if seed in player_values[key]: print('Boomed seed: {}'.format(seed)) boomed_seeds.append(seed) surviving_seeds -= 1 break print('Number of surviving seeds: {}'.format(surviving_seeds)) result = sim.run(G_json, player_values) print('Results for round {}'.format(round)) pprint.pprint(result) # Store score of winner players = list(result.keys()) winner = max(players, key=lambda player: result[player]) final_scores[winner] += 1 print('Final Scores') pprint.pprint(final_scores)
import matplotlib.pyplot as plt ## Importing my own functions import plotting import initialise_random_particles import sim import functions ## Setting paramters m0 = 1 n = 2500 N = n * 2 r0 = 0.001 r = np.full(N, r0) v0 = 1 m = np.zeros(N) m[:n] = m0 m[n:] = 4 * m0 #run for xi = 1 ksis = [1, 0.9, 0.8] for ksi in ksis: x, y, vx, vy = initialise_random_particles.initialise(N, r, v0) p3_data = sim.run(x, y, vx, vy, r, m, 15 * n, ksi, 3) plotting.kinetic_energy_aft(p3_data)
if a.animate: if not os.path.isdir(a.fpath): os.mkdir(a.fpath) elif len(os.listdir(a.fpath)) != 0: print( "It is not recommended to place animation frames in a non-empty directory. Do you still wish to proceed? [Y/N]" ) choice: str = input() if choice.upper() != 'Y': sys.exit(0) sim.run(a.lim, a.n_atoms, a.vol, a.U, a.mass, a.radius, animate=a.animate, interact=True, fpath=a.fpath) elif a.mode == 'vsweep': if not os.path.isdir(a.dpath): os.mkdir(a.dpath) sr.volume_sweep(a.lim, a.n_atoms, a.U, a.mass, a.radius, a.num_points, dpath=a.dpath) elif a.mode == 'tsweep':
G.add_node(i) for j in range(len(data[str(i)])): G.add_edge(i, int(data[str(i)][j])) return (num_players, num_seeds, data, G) def writeseeds(seeds): # Re-use the same seeds for every round for j in range(NUM_ROUNDS): for i in range(num_seeds): print seeds[i] if __name__ == "__main__": if(len(sys.argv) < 3): print "python main.py <json_file> [strategies...]" sys.exit(-1); # Parse the JSON file into a graph. (num_players, num_seeds, data, G) = scanfile(sys.argv[1]) # Generate the seeds based on graph data. nodes = {} for i in range(2, len(sys.argv)): seeds = __import__(sys.argv[i]).generate_seeds(num_players, num_seeds, G) seeds = map(str, list(seeds))[:num_seeds] nodes[sys.argv[i]] = seeds print sim.run(data, nodes)
#Step one: initialize particles and test the packing factor x,y,vx,vy = initialise_random_particles.initialise_p4(n, v0, r) #np.save('p4data3.npy',[x,y,vx,vy]) #Loading saved particle positions [x,y,vx,vy] = np.load('p4data3.npy') #copying initial position to be avle to compare against after the simulation. x_ini = np.copy(x) y_ini = np.copy(y) plotting.particle_pos_p4(x,y) sim.run(x,y,vx,vy,r,m,1000000,ksi,4) plotting.particle_pos_p4(x,y) crater_size = functions.crater_size(x_ini,y_ini,x,y) print('crater size',crater_size) #sweep of velocity # crater_sizes = [] # m0s = np.linspace(2,50,10) # for m0 in m0s: # [x,y,vx,vy] = np.load('p4data3.npy') # m[0] = m0 # sim.run4(x,y,vx,vy,r,m,1000000,ksi,4) # cs = functions.crater_size(x_ini,y_ini,x,y) # plotting.particle_pos_p4(x,y)
# Dictionary with node # as the key and the value is the degree's centrality deg_centrality = nx.degree_centrality(G) opponent_nodes = sorted(deg_centrality, key=deg_centrality.get)[::-1][:needed] return opponent_nodes # This function just gets the top n nodes with the highest degree-centrality def get_nodes(num, data): needed = int(num) # Data is a dictionary with the keys as strings, value list of strings G = nx.from_dict_of_lists(data) # Dictionary with node # as the key and the value is the degree's centrality deg_centrality = nx.degree_centrality(G) #Sorted order of nodes with the highest degree-centrality our_nodes = sorted(deg_centrality, key=deg_centrality.get)[::-1] return our_nodes[:needed] # We call the sim.py file so that we can see if this will work each time if __name__ == "__main__": file = sys.argv[1] with open(file) as json_file: data = json.load(json_file) their_nodes = get_opponent_nodes(int(sys.argv[2])*0.80, data) our_nodes = get_nodes(int(sys.argv[2]), data) strat = {"ours" : our_nodes, "theirs" : their_nodes} print(sim.run(data, strat))
# print "-" * 20 # print "strategies:" d = nx.closeness_centrality(G) sorted_centrality_nodes = sorted(d.keys(), key=lambda k: d[k], reverse=True) deg_centrality_nodes = sorted_centrality_nodes[:N] # d = nx.communicability_centrality(G) # sorted_centrality_nodes = sorted(d.keys(), key=lambda k: d[k], reverse=True) # comm_centrality_nodes = sorted_centrality_nodes[:N] d = betweenness_centrality.betweenness_centrality_parallel(G) sorted_centrality_nodes = sorted(d.keys(), key=lambda k: d[k], reverse=True) btwn_centrality_nodes = sorted_centrality_nodes[:N] # for node in btwn_centrality_nodes: # print node graph = nx.to_dict_of_lists(G) nodes = {"btwn_centrality": btwn_centrality_nodes, "closeness_centrality": deg_centrality_nodes} s = sim.run(graph, nodes) print s #d = nx.betweenness_centrality(G) #btwn = heap.nlargest(N, d, key = lambda k: d[k])