code
stringlengths
17
6.64M
class Cascading(Simulation): '\n This class simulates cascading failures on a network :cite:`crucitti2004model`.\n\n :param graph: an undirected NetworkX graph\n :param runs: an integer number of times to run the simulation\n :param steps: an integer number of steps to run a single simulation\n :pa...
def main(): graph = electrical() params = {'runs': 1, 'steps': 100, 'seed': 1, 'l': 0.8, 'r': 0.2, 'c': int((0.1 * len(graph))), 'k_a': 5, 'attack': 'id_node', 'attack_approx': None, 'k_d': 0, 'defense': None, 'robust_measure': 'largest_connected_component', 'plot_transition': False, 'gif_animation': True, 'g...
def run_defense_method(graph, method, k=3, seed=None): '\n Runs a specified defense on an undirected graph, returning a list of nodes to defend.\n\n :param graph: an undirected NetworkX graph\n :param method: a string representing one of the attack methods\n :param k: number of nodes or edges to attac...
def get_defense_methods(): '\n Gets a list of available defense methods as a list of functions.\n\n :return: a list of all defense functions\n ' return methods.keys()
def get_defense_category(method): "\n Gets the defense category e.g., 'node', 'edge' defense.\n\n :param method: a string representing the defense method\n :return: a string representing the defense type ('node' or 'edge')\n " category = None if (method in categories): category = categ...
def get_node_ns(graph, k=3): '\n Get k nodes to defend based on the Netshield algorithm :cite:`tong2010vulnerability`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of nodes to defend\n\n :return: a list of nodes to defend\n ' return get_node_ns_attack(graph, k)
def get_node_pr(graph, k=3): '\n Get k nodes to defend based on top PageRank entries :cite:`page1999pagerank`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of nodes to defend\n\n :return: a list of nodes to defend\n ' return get_node_pr_attack(graph, k)
def get_node_eig(graph, k=3): '\n Get k nodes to defend based on top eigenvector centrality entries\n\n :param graph: an undirected NetworkX graph\n :param k: number of nodes to defend\n :return: a list of nodes to defend\n ' return get_node_eig_attack(graph, k)
def get_node_ib(graph, k=3, approx=np.inf): '\n Get k nodes to defend based on Initial Betweenness (IB) Removal :cite:`holme2002attack`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of nodes to defend\n :param approx: number of nodes to approximate the betweenness centrality, k=0....
def get_node_rb(graph, k=3, approx=np.inf): '\n Get k nodes to defend based on Recalculated Betweenness (RB) Removal :cite:`holme2002attack`\n\n :param graph: an undirected NetworkX graph\n :param k: number of nodes to defend\n :param approx: number of nodes to approximate the betweenness centrality, ...
def get_node_id(graph, k=3): '\n Get k nodes to defend based on Initial Degree (ID) Removal :cite:`holme2002attack`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of nodes to defend\n\n :return: a list of nodes to defend\n ' return get_node_id_attack(graph, k)
def get_node_rd(graph, k=3): '\n Get k nodes to defend based on Recalculated Degree (RD) Removal :cite:`holme2002attack`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of nodes to defend\n\n :return: a list of nodes to defend\n ' return get_node_rd_attack(graph, k)
def get_node_rnd(graph, k=3): '\n Randomly select k distinct nodes to defend\n\n :param graph: an undirected NetworkX graph\n :param k: number of nodes to defend\n\n :return: a list of nodes to defend\n ' return get_node_rnd_attack(graph, k)
def get_central_edges(graph, k, method='eig'): '\n Internal function to compute edge PageRank, eigenvector centrality and degree centrality\n\n :param graph: undirected NetworkX graph\n :param k: int number of nodes to defend\n :param method: string representing defense method\n :return: list of ed...
def add_edge_pr(graph, k=3): "\n Get k edges to defend based on top edge PageRank entries :cite:`tong2012gelling`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of edges to add\n :return: a dictionary of the edges to be 'added'\n " info = defaultdict(list) info['added'] ...
def add_edge_eig(graph, k=3): "\n Get k edges to defend based on top edge eigenvector centrality entries :cite:`tong2012gelling`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of edges to add\n :return: a dictionary of the edges to be 'added'\n " info = defaultdict(list) ...
def add_edge_degree(graph, k=3): '\n Add k edges to defend based on top edge degree centrality entries :cite:`tong2012gelling`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of edges to add\n :return: a list of edges to add\n ' info = defaultdict(list) info['added'] = ge...
def add_edge_rnd(graph, k=3): "\n Add k random edges to the graph\n\n :param graph: an undirected NetworkX graph\n :param k: number of edges to add\n :return: a dictionary of the edges to be 'added'\n " graph_ = graph.copy() info = defaultdict(list) for _ in range(k): nodes = gr...
def add_edge_pref(graph, k=3): "\n Adds an edge connecting two nodes with the lowest degrees :cite:`beygelzimer2005improving`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of edges to add\n :return: a dictionary of the edges to be 'added'\n " info = defaultdict(list) de...
def rewire_edge_rnd(graph, k=3): "\n Removes a random edge and adds one randomly :cite:`beygelzimer2005improving`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of edges to rewire\n :return: a dictionary of the edges to be 'removed' and edges to be 'added'\n " info = default...
def rewire_edge_rnd_neighbor(graph, k=3): "\n Randomly selects a neighbor of a node and removes the edge; then adds a random edge :cite:`beygelzimer2005improving`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of edges to rewire\n :return: a dictionary of the edges to be 'removed' ...
def rewire_edge_pref(graph, k=3): "\n Selects node with highest degree, randomly removes a neighbor; adds edge to random node in graph :cite:`beygelzimer2005improving`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of edges to rewire\n :return: a dictionary of the edges to be 'remo...
def rewire_edge_pref_rnd(graph, k=3): "\n Selects an edge, disconnects the higher degree node, and reconnects to a random one :cite:`beygelzimer2005improving`.\n\n :param graph: an undirected NetworkX graph\n :param k: number of edges to rewire\n :return: a dictionary of the edges to be 'removed' and ...
class Defense(Simulation): '\n This class simulates a variety of defense techniques on an undirected NetworkX graph\n\n :param graph: an undirected NetworkX graph\n :param runs: an integer number of times to run the simulation\n :param steps: an integer number of steps to run a single simulation\n ...
def main(): graph = graph_loader(graph_type='ky2', seed=1) params = {'runs': 1, 'steps': 30, 'seed': 1, 'attack': 'rb_node', 'k_a': 30, 'attack_approx': int((0.1 * len(graph))), 'defense': 'add_edge_random', 'robust_measure': 'largest_connected_component', 'plot_transition': True, 'gif_animation': True, 'edge...
class Diffusion(Simulation): '\n Simulates the propagation of a virus using either the SIS or SIR model :cite:`kermack1927contribution`.\n\n :param graph: contact network\n :param model: a string to set the model type (i.e., SIS or SIR)\n :param runs: an integer number of times to run the simulation\n...
def main(): graph = as_733() sis_params = {'model': 'SIS', 'b': 0.001, 'd': 0.01, 'c': 1, 'runs': 1, 'steps': 5000, 'seed': 1, 'diffusion': 'min', 'method': 'ns_node', 'k': 5, 'plot_transition': True, 'gif_animation': True, 'edge_style': 'bundled', 'node_style': 'force_atlas', 'fa_iter': 20} ds = Diffusio...
def graph_loader(graph_type, **kwargs): "\n Loads any of the available graph models, supported user-downloaded datasets and toy graphs.\n In order to get a list of available graph options run 'get_graph_options()'.\n\n :param graph_type: a string representing the graph you want to load. For example, 'ER'...
def download_dataset(dataset): '\n Reading the dataset from the web.\n\n :param dataset: a string representing the dataset to download\n ' url_path = graph_urls[dataset][0] local_path = (graph_dir + url_path.split('datasets/')[1]) if (not os.path.exists(local_path)): urllib.request.ur...
def get_graph_urls(): '\n Returns a dictionary of the datasets used in TIGER and the original link to download them\n\n :return: dictionary containing links to each dataset\n ' return graph_urls
def get_graph_options(): '\n Returns a formatted string containing all of the generators, datasets and custom graphs implemented in TIGER\n\n :return: formatted string\n ' graph_options = {'models': list(models.keys()), 'datasets': datasets, 'custom': list(custom.keys())} return json.dumps(graph_...
def erdos_reyni(n, p=None, seed=None): '\n Returns a Erdos Reyni NetworkX graph\n\n :param n: number of nodes\n :param p: probability for edge creation\n :param seed: fixes the graph generation process\n :return: a NetworkX graph\n ' if (p is None): p = ((1.0 / n) + 0.1) return n...
def watts_strogatz(n, m=4, p=0.05, seed=None): '\n Returns a Watts Strogatz NetworkX graph\n\n :param n: number of nodes\n :param m: each node is joined with its k nearest neighbors in a ring topology\n :param p: probability of rewiring each edge\n :param seed: fixes the graph generation process\n ...
def barabasi_albert(n, m=3, seed=None): '\n Returns a Barabasi Albert NetworkX graph\n\n :param n: number of nodes\n :param m: number of edges to attach from a new node to existing nodes\n :param seed: fixes the graph generation process\n :return: a NetworkX graph\n ' return nx.generators.ba...
def clustered_scale_free(n, m=3, p=0.3, seed=None): '\n Returns a Clustered Scale-Free NetworkX graph\n\n :param n: number of nodes\n :param m: the number of random edges to add for each new node\n :param p: probability of adding a triangle after adding a random edge\n :param seed: fixes the graph...
def wdn_ky2(): '\n Returns the graph from: https://uknowledge.uky.edu/wdst/4/,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.Graph() with open((graph_dir + 'ky2.txt')) as f: lines = f.readlines() for ...
def as_733(): "\n Returns the 'as19971108' graph from: http://snap.stanford.edu/data/as-733.html,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n " graph = nx.read_edgelist((graph_dir + 'as19971108.txt')) graph = nx.convert_node_la...
def p2p_gnuetella08(): '\n Returns the graph from: https://snap.stanford.edu/data/p2p-Gnutella08.html,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.read_edgelist((graph_dir + 'p2p-Gnutella08.txt')) return graph.subg...
def ca_grqc(): '\n Returns the graph from: https://snap.stanford.edu/data/ca-GrQc.html,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.read_edgelist((graph_dir + 'ca-GrQc.txt')) return graph.subgraph(max(nx.connected_...
def cit_hep_th(): '\n Returns the graph from: https://snap.stanford.edu/data/cit-HepTh.html,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.read_edgelist((graph_dir + 'cit-HepTh.txt')) return graph.subgraph(max(nx.con...
def wiki_vote(): '\n Returns the graph from: https://snap.stanford.edu/data/wiki-Vote.html,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.read_edgelist((graph_dir + 'wiki-Vote.txt')) return graph.subgraph(max(nx.conn...
def email_eu_all(): '\n Returns the graph from: https://snap.stanford.edu/data/email-EuAll.html,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.read_edgelist((graph_dir + 'email-EuAll.txt')) return graph.subgraph(max(...
def dblp(): '\n Returns the graph from: https://snap.stanford.edu/data/com-DBLP.html,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.read_edgelist((graph_dir + 'dblp.txt')) return graph.subgraph(max(nx.connected_compo...
def ca_astro_ph(): '\n Returns the graph from: https://snap.stanford.edu/data/ca-AstroPh.html,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.read_edgelist((graph_dir + 'ca-AstroPh.txt')) return graph.subgraph(max(nx....
def ca_hep_th(): '\n Returns the graph from: https://snap.stanford.edu/data/cit-HepTh.html,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.read_edgelist((graph_dir + 'ca-HepTh.txt')) return graph.subgraph(max(nx.conne...
def enron_email(): '\n Returns the graph from: https://snap.stanford.edu/data/email-Enron.html,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.read_edgelist((graph_dir + 'email-enron.txt')) return graph.subgraph(max(n...
def karate(): '\n Returns the graph from: https://networkx.org/documentation/stable/reference/generated/networkx.generators.social.karate_club_graph.html,\n\n :return: undirected NetworkX graph\n ' return nx.karate_club_graph()
def oregeon_1(): '\n Returns the graph from: https://snap.stanford.edu/data/oregon1_010331.html,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.read_edgelist((graph_dir + 'as-oregon1.txt')) return graph.subgraph(max(n...
def electrical(): '\n Returns the graph from: http://konect.cc/networks/opsahl-powergrid/,\n where we preprocess it to only keep the largest connected component\n\n :return: undirected NetworkX graph\n ' graph = nx.read_gml((graph_dir + 'power.gml'), label='id') return graph.subgraph(max(nx.co...
def o4_graph(): '\n Returns a 4 node disconnected graph\n\n :return: undirected NetworkX graph\n ' G = nx.Graph() G.add_nodes_from([0, 1, 2, 3]) return G
def p4_graph(): '\n Returns a 4 node path graph\n\n :return: undirected NetworkX graph\n ' G = nx.Graph() G.add_edges_from([(0, 1), (1, 2), (2, 3)]) return G
def s4_graph(): '\n Returns a 4 node star graph\n\n :return: undirected NetworkX graph\n ' G = nx.Graph() G.add_edges_from([(0, 1), (1, 2), (1, 3)]) return G
def c4_graph(): '\n Returns a 4 node cycle graph\n\n :return: undirected NetworkX graph\n ' G = nx.Graph() G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)]) return G
def k4_1_graph(): '\n Returns a 4 node diamond graph (1 diagonal edge)\n\n :return: undirected NetworkX graph\n ' G = nx.Graph() G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 3), (2, 3)]) return G
def k4_2_graph(): '\n Returns a 4 node diamond graph (2 diagonal edges), a.k.a. complete graph\n\n :return: undirected NetworkX graph\n ' G = nx.Graph() G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 3), (1, 2), (2, 3)]) return G
def two_c4_0_bridge(): '\n Returns two disconnected 4 node cycle graphs\n\n :return: undirected NetworkX graph\n ' G = nx.Graph() G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (4, 5), (5, 6), (6, 7), (7, 4)]) return G
def two_c4_1_bridge(): '\n Returns two 4 node cycle graphs connected by 1 edge\n\n :return: undirected NetworkX graph\n ' G = nx.Graph() G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (4, 5), (5, 6), (6, 7), (7, 4), (2, 4)]) return G
def two_c4_2_bridge(): '\n Returns two 4 node cycle graphs connected by 2 edges\n\n :return: undirected NetworkX graph\n ' G = nx.MultiGraph() G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (4, 5), (5, 6), (6, 7), (7, 4), (2, 4), (2, 4)]) return G
def two_c4_3_bridge(): '\n Returns two 4 node cycle graphs connected by 3 edges\n\n :return: undirected NetworkX graph\n ' G = nx.MultiGraph() G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (4, 5), (5, 6), (6, 7), (7, 4), (2, 4), (2, 4), (2, 4)]) return G
class Simulation(): '\n The parent class for all simulation classes i.e., attack, defense, cascading failure and diffusion models.\n Provides a shared set of functions, largely for network visualization and plotting of results\n\n :param graph: undirected NetworkX graph\n :param runs: number of times ...
def gpu_available(): from pip._internal.utils.misc import get_installed_distributions gpu = False installed_packages = [package.project_name for package in get_installed_distributions()] if any((('cupy' in s) for s in installed_packages)): gpu = True return gpu
def get_sparse_graph(graph): '\n Returns a sparse adjacency matrix in CSR format\n\n :param graph: undirected NetworkX graph\n :return: Scipy sparse adjacency matrix\n ' return nx.to_scipy_sparse_matrix(graph, format='csr', dtype=float, nodelist=graph.nodes)
def get_adjacency_spectrum(graph, k=np.inf, eigvals_only=False, which='LA', use_gpu=False): '\n Gets the top k eigenpairs of the adjacency matrix\n\n :param graph: undirected NetworkX graph\n :param k: number of top k eigenpairs to obtain\n :param eigvals_only: get only the eigenvalues i.e., no eigenv...
def get_laplacian_spectrum(graph, k=np.inf, which='SM', tol=0.01, eigvals_only=True, use_gpu=False): '\n Gets the bottom k eigenpairs of the Laplacian matrix\n\n :param graph: undirected NetworkX graph\n :param k: number of bottom k eigenpairs to obtain\n :param which: he type of k eigenvectors and e...
def get_laplacian(graph): '\n Gets the Laplacian matrix in sparse CSR format\n\n :param graph: undirected NetworkX graph\n :return: Scipy sparse Laplacian matrix\n ' A = nx.to_scipy_sparse_matrix(graph, format='csr', dtype=np.float, nodelist=graph.nodes) D = sparse.spdiags(data=A.sum(axis=1).f...
def test_attack_strength(): '\n check that valid nodes are returned\n :return:\n ' graph = karate() methods = get_attack_methods() strength = list(range(1, 20)) for method in methods: for k in strength: nodes = run_attack_method(graph, method=method, k=k) a...
def test_method_selection(): '\n check that valid nodes are returned\n :return:\n ' ground_truth = {'ns_node': ([33, 0, 2, 32], [33, 2, 0, 32]), 'pr_node': [33, 0, 32, 2], 'eig_node': [33, 0, 2, 32], 'id_node': [33, 0, 32, 2], 'rd_node': [33, 0, 32, 1], 'ib_node': [0, 33, 32, 2], 'rb_node': [0, 33, 3...
def main(): test_method_selection() test_attack_strength()
def test_defense_strength(): '\n check that valid nodes are returned\n :return:\n ' graph = karate() methods = get_defense_methods() strength = list(range(1, 20)) for method in methods: if (get_defense_category(method) == 'node'): for k in strength: nod...
def test_method_selection(): '\n check that valid nodes are returned\n :return:\n ' ground_truth = {'ns_node': ([33, 0, 2, 32], [33, 2, 0, 32]), 'pr_node': [33, 0, 32, 2], 'eig_node': [33, 0, 2, 32], 'id_node': [33, 0, 32, 2], 'rd_node': [33, 0, 32, 1], 'ib_node': [0, 33, 32, 2], 'rb_node': [0, 33, 3...
def main(): test_defense_strength() test_method_selection()
def test_measures(): ground_truth = {'node_connectivity': [0, 1, 2, 2, 3, 0, 1, 1, 1], 'edge_connectivity': [0, 1, 2, 2, 3, 0, 1, 1, 1], 'diameter': [None, 3, 2, 2, 1, None, 5, 5, 5], 'average_distance': [None, 1.67, 1.33, 1.17, 1, None, 2.29, 2.29, 2.29], 'average_inverse_distance': [0, 0.72, 0.83, 0.92, 1.0, 0....
def main(): test_measures()
def test_sis_model(): params = {'model': 'SIS', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 10, 'steps': 5000, 'diffusion': 'max', 'method': 'add_edge_random', 'k': 15, 'seed': 1, 'plot_transition': False, 'gif_animation': False} graph = karate() ds = Diffusion(graph, **params) increased_diffusion = ds.r...
def test_sir_model(): params = {'model': 'SIR', 'b': 0.00208, 'd': 0.01, 'c': 0.1, 'runs': 10, 'steps': 5000, 'diffusion': 'max', 'method': 'add_edge_random', 'k': 40, 'seed': 1, 'plot_transition': False, 'gif_animation': False} graph = karate() ds = Diffusion(graph, **params) increased_diffusion = ds...
def test_cascading(): params = {'runs': 10, 'steps': 30, 'l': 0.8, 'r': 0.5, 'capacity_approx': np.inf, 'k_a': 4, 'attack': 'rnd_node', 'k_d': 0, 'defense': None, 'robust_measure': 'largest_connected_component', 'seed': 1, 'plot_transition': False, 'gif_animation': False} graph = karate() cf = Cascading(g...
def main(): test_sis_model() test_sir_model() test_cascading()
def run_test(params): graph = karate() ds = Diffusion(graph, **params) ds.run_simulation()
def test_animation(): params = {'model': 'SIS', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 10, 'steps': 500, 'seed': 1, 'diffusion': 'max', 'method': 'add_edge_random', 'k': 15, 'plot_transition': False, 'gif_animation': True} run_test(params)
def test_transition(): params = {'model': 'SIS', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 10, 'steps': 500, 'seed': 1, 'diffusion': 'max', 'method': 'add_edge_random', 'k': 15, 'plot_transition': True, 'gif_animation': False} run_test(params)
def test_gif_snaps(): params = {'model': 'SIS', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 10, 'steps': 500, 'seed': 1, 'diffusion': 'max', 'method': 'add_edge_random', 'k': 15, 'plot_transition': False, 'gif_animation': True, 'gif_snaps': True} run_test(params)
def test_force_atlas(): params = {'model': 'SIR', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 10, 'steps': 500, 'seed': 1, 'diffusion': 'max', 'method': 'add_edge_random', 'k': 15, 'edge_style': None, 'node_style': 'force_atlas', 'fa_iter': 200, 'plot_transition': True, 'gif_animation': False} run_test(params)
def test_edge_bundling(): params = {'model': 'SIS', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 10, 'steps': 500, 'seed': 1, 'diffusion': 'max', 'method': 'add_edge_random', 'k': 15, 'edge_style': 'bundled', 'node_style': 'force_atlas', 'fa_iter': 200, 'plot_transition': True, 'gif_animation': False} run_test(pa...
def main(): test_animation() test_transition() test_gif_snaps() test_force_atlas() test_edge_bundling()
def gps2coordinate(p2, p1): x = vincenty(p1, (p2[0], p1[1])).meters y = vincenty(p1, (p1[0], p2[1])).meters x = ((- x) if (p2[0] < p1[0]) else x) y = ((- y) if (p2[1] < p1[1]) else y) return [round(x, 6), round(y, 6)]
def get_coordinates(records): global start_location if (start_location == None): start_location = (records[0]['x'], records[0]['y']) for r in records: coord = gps2coordinate((r['x'], r['y']), start_location) r['x'] = coord[0] r['y'] = coord[1] return records
def read_records(input_records_file, gps_type): lines = open(input_records_file).readlines()[1:] records = [l.strip().split(' ') for l in lines] records = np.array([(r[0], float(r[1]), float(r[2])) for r in records], dtype=[('name', object), ('x', float), ('y', float)]) return records
def main(args): train_records = read_records(args.train_list, args.gps_type) train_names = [r[0] for r in train_records] test_records = read_records(args.test_list, args.gps_type) test_names = [r[0] for r in test_records] name2vlad = np.load(args.vlad_features)['name2vlad'].item() print(len(tr...
class PGNetwork(nn.Module): def __init__(self, state_dim, action_dim): '\n Initialize PGNetwork.\n :param state_dim: dimension of the state\n :param action_dim: dimension of the action\n ' super(PGNetwork, self).__init__() self.fc1 = nn.Linear(state_dim, 20) ...
class Actor(object): def __init__(self, state_dim, action_dim, device, LR): self.state_dim = state_dim self.action_dim = action_dim self.device = device self.LR = LR self.network = PGNetwork(state_dim=self.state_dim, action_dim=self.action_dim).to(self.device) self...
class QNetwork(nn.Module): def __init__(self, state_dim, action_dim): super(QNetwork, self).__init__() self.fc1 = nn.Linear(state_dim, 20) self.fc2 = nn.Linear(20, 1) def forward(self, x): out = F.relu(self.fc1(x)) out = self.fc2(out) return out def initi...
class Critic(object): def __init__(self, state_dim, action_dim, device, LR, GAMMA): self.state_dim = state_dim self.action_dim = action_dim self.device = device self.LR = LR self.GAMMA = GAMMA self.network = QNetwork(state_dim=self.state_dim, action_dim=self.action...
class RLForest(): def __init__(self, width_rl, height_rl, device, LR, GAMMA, stop_num, r_num): '\n Initialize the RL Forest.\n :param width_rl: width of each relation tree\n :param height_rl: height of each relation tree\n :param device: "cuda" / "cpu"\n :param LR: Acto...
def get_scores(scores, labels): '\n Get the scores of current batch.\n :param scores: the neighbor nodes label-aware scores for each relation\n :param labels: the batch node labels used to select positive nodes\n :returns: the state of current batch\n ' relation_scores = [] pos_index = (lab...
class GraphSage(nn.Module): '\n\tVanilla GraphSAGE Model\n\tCode partially from https://github.com/williamleif/graphsage-simple/\n\t' def __init__(self, num_classes, enc): super(GraphSage, self).__init__() self.enc = enc self.xent = nn.CrossEntropyLoss() self.weight = nn.Param...
class MeanAggregator(nn.Module): "\n\tAggregates a node's embeddings using mean of neighbors' embeddings\n\t" def __init__(self, features, cuda=False, gcn=False): '\n\t\tInitializes the aggregator for a specific graph.\n\n\t\tfeatures -- function mapping LongTensor of node ids to FloatTensor of featu...
class Encoder(nn.Module): "\n\tVanilla GraphSAGE Encoder Module\n\tEncodes a node's using 'convolutional' GraphSage approach\n\t" def __init__(self, features, feature_dim, embed_dim, adj_lists, aggregator, num_sample=10, base_model=None, gcn=False, cuda=False, feature_transform=False): super(Encoder,...
class OneLayerRio(nn.Module): '\n\tThe Rio-GNN model in one layer\n\t' def __init__(self, num_classes, inter1, lambda_1): '\n\t\tInitialize the Rio-GNN model\n\t\t:param num_classes: number of classes (2 in our paper)\n\t\t:param inter1: the inter-relation aggregator that output the final embedding\n...
class TwoLayerRio(nn.Module): '\n\tThe Rio-GNN model in one layer\n\t' def __init__(self, num_classes, inter1, inter2, lambda_1, last_label_scores): '\n\t\tInitialize the Rio-GNN model\n\t\t:param num_classes: number of classes (2 in our paper)\n\t\t:param inter1: the inter-relation aggregator that o...
class Vgg16(torch.nn.Module): def __init__(self, device='cpu'): super(Vgg16, self).__init__() vgg_pretrained_features = vgg16(pretrained=True).features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Sequential() self.slice3 = torch.nn.Sequential() self....