def setup_class(cls): cls.G = nx.path_graph(9) cls.DG = nx.path_graph(9, create_using=nx.DiGraph()) cls.MG = nx.path_graph(9, create_using=nx.MultiGraph()) cls.MDG = nx.path_graph(9, create_using=nx.MultiDiGraph()) cls.Gv = nx.to_undirected(cls.DG) cls.DGv = nx.to_directed(cls.G) cls.MGv = nx.to_undirected(cls.MDG) cls.MDGv = nx.to_directed(cls.MG) cls.Rv = cls.DG.reverse() cls.MRv = cls.MDG.reverse() cls.graphs = [ cls.G, cls.DG, cls.MG, cls.MDG, cls.Gv, cls.DGv, cls.MGv, cls.MDGv, cls.Rv, cls.MRv, ] for G in cls.graphs: G.edges, G.nodes, G.degree
def draw_dependency_graph(classes, analysis): G = nx.DiGraph(directed=True) nx.to_directed(G) max_dep = 0 for class_object in classes: num_dep = len(class_object.dependencies) if (num_dep > max_dep): max_dep = num_dep for class_object in classes: G.add_node(class_object.name) for dependency in class_object.dependencies: G.add_edge(class_object.name, dependency) pos = nx.circular_layout(G) options = { 'pos': pos, 'with_labels': True, 'arrows': True, 'node_color': '#6e52ff', 'node_size': 1000, 'width': 1, 'arrowstyle': '-|>', 'arrowsize': 12, } nx.draw(G, **options) plt.annotate(analysis, (-1, 1.25)) plt.savefig("dependency_graph.png")
def estatisticas(endereco, arq): arquivo = open(endereco + '/' + arq + '_estatisticas.csv', 'w') e = endereco + '/' + arq + 'Convertido.redeFras.csv' graph = nx.read_edgelist(e) nx.to_directed(graph) clust_coeficients = nx.clustering(graph) dict_betweenes = nx.betweenness_centrality(graph) closeness = nx.closeness_centrality(graph) eigenvector_centrality = nx.eigenvector_centrality(graph) centralidade_grau = nx.degree_centrality(graph) grau = nx.degree(graph) #modularidade = nx.modularity_matrix(graph) #centro= nx.center(graph,e=None, usebounds=False) # diametro= nx.diameter(graph,e=None, usebounds=False) densidade = nx.density(graph) print densidade arquivo.write( "No ; Grau ; Betweennes ; Centralidade_Grau ; Centralidade(Closeness) ; Eigenvector_Centrality ; Clustering\n" ) for key in dict_betweenes.keys(): aux = str(dict_betweenes[key]) aux1 = str(grau[key]) aux2 = str(centralidade_grau[key]) aux3 = str(closeness[key]) aux4 = str(eigenvector_centrality[key]) aux5 = str(clust_coeficients[key]) arquivo.write(key + ' ; ' + aux1 + ' ; ' + aux + ' ; ' + aux2 + ' ; ' + aux3 + ' ; ' + aux4 + ' ; ' + aux + '\n') arquivo.close()
def node_label_to_int(graphs, flag): GS = [] for g in graphs: if flag == 1: GS.append(nx.to_directed(nx.relabel_nodes(g, lambda x: int(x) - 1))) else: GS.append(nx.to_directed(nx.relabel_nodes(g, lambda x: int(x)))) return GS
def store_graph(self, observed_graph_name="observed.edgelist", complete_graph_name="all.edgelist"): nx.write_edgelist(nx.to_directed(self.observed_graph), observed_graph_name, data=False, delimiter='\t') nx.write_edgelist(nx.to_directed(self.graph), complete_graph_name, data=False, delimiter='\t') logging.info( f"write observed graph to {observed_graph_name} and complete graph to {complete_graph_name}" )
def _to_edgelist(self): g = nx.to_directed(self.graph) g = nx.convert_node_labels_to_integers(g) self.edgeindex = [[x[0], x[1]] for x in g.edges] self.edge_feature = [g.edges[x[0], x[1]]["length"] for x in g.edges] self.pos = [g.nodes[n]["pos"] for n in g] self.dof = [g.nodes[n]["dof"] for n in g]
def save_graph(G, output_path, delimiter=',', write_stats=True): r""" Saves a graph to a file as an edgelist. If the stats parameter is set to True the file will include several lines containing the same basic graph statistics as provided by the get_stats function. Parameters ---------- G : graph A NetworkX graph output_path : file or string File or filename to write. If a file is provided, it must be opened in 'wb' mode. delimiter : string, optional The string used to separate values. Default is ','. write_stats : bool, optional Sets if graph statistics should be added to the edgelist or not. Default is True. """ # Write the graph stats in the file if required if write_stats: get_stats(G, output_path) # Open the file where data should be stored f = open(output_path, 'a+b') # Write the graph to a file and use both edge directions if graph is undirected if G.is_directed(): # Store edgelist nx.write_edgelist(G, f, delimiter=delimiter, data=False) else: H = nx.to_directed(G) # Store edgelist nx.write_edgelist(H, f, delimiter=delimiter, data=False)
def nx_to_openne_graph(nxgraph): dg = nx.to_directed(nxgraph) nx.set_edge_attributes(dg, 1.0, 'weight') g = graph.Graph() g.G = dg g.encode_node() return g
def simpleStar(subset, center, direction=ut.Direction.OUTGOING): """ create a star graph on the input nodes subset with node i as the center """ n = len(subset) if n == 0: raise NameError('There needs to be at least one node') res = np.where(subset == center) if len(res[0]) == 0: raise NameError('node ' + str(center) + ' is not in the subset') centerIndex = res[0][0] D = dict(zip(np.array([i for i in range(n)]), subset)) D[0], D[centerIndex] = center, subset[0] G = nx.star_graph(n-1) G = nx.to_directed(G) G = nx.DiGraph(G) if direction == ut.Direction.OUTGOING: G.remove_edges_from([(i, 0) for i in range(n)]) elif direction == ut.Direction.INCOMING: G.remove_edges_from([(0, i) for i in range(n)]) else: raise NameError(str(direction) + ' is not a valid value for direction') G = nx.relabel_nodes(G, D) ut.normalizeGraph(G) return G
def random_grid_model(dim): layer_grid = create_empty_copy( nx.to_directed(nx.grid_2d_graph(dim[0], dim[1]))) for node in layer_grid.nodes.values(): if global_vars.get('simple_start'): node['layer'] = IdentityLayer() else: node['layer'] = random_layer() layer_grid.add_node('input') layer_grid.nodes['input']['layer'] = IdentityLayer() if global_vars.get('grid_as_ensemble'): for row in range(dim[0]): layer_grid.add_node(f'output_conv_{row}') layer_grid.nodes[f'output_conv_{row}']['layer'] = IdentityLayer() layer_grid.add_edge((row, dim[1] - 1), f'output_conv_{row}') else: layer_grid.add_node('output_conv') layer_grid.nodes['output_conv']['layer'] = IdentityLayer() layer_grid.add_edge((0, dim[1] - 1), 'output_conv') layer_grid.add_edge('input', (0, 0)) for i in range(dim[1] - 1): layer_grid.add_edge((0, i), (0, i + 1)) layer_grid.graph['height'] = dim[0] layer_grid.graph['width'] = dim[1] if global_vars.get('parallel_paths_experiment'): set_parallel_paths(layer_grid) if check_legal_grid_model(layer_grid): return layer_grid else: return random_grid_model(dim)
def data_to_graph(self, raw_data, max_nodes): graph_data = dict() state = raw_data for n in self.graph.nodes: start = self._shift + self.graph.nodes.data()[n]['pos'] end = start + self.graph.nodes.data()[n]['dof'] if start < self._shift: x = np.zeros(1, dtype=np.float32) else: x = state[start:end] graph_data[n] = x x = torch.as_tensor([graph_data[n] for n in self.graph.nodes], dtype=torch.float32) node_feature = torch.zeros((max_nodes, 1), dtype=torch.float) node_feature[:x.shape[0]] = x g = nx.to_directed(self.graph) g = nx.convert_node_labels_to_integers(g) edge_index = torch.as_tensor([[x[0], x[1]] for x in g.edges], dtype=torch.long).t() edge_feature = torch.as_tensor( [g.edges[x[0], x[1]]["length"] for x in g.edges], dtype=torch.float32) root_feature = torch.as_tensor(state[:5], dtype=torch.float) mask = torch.as_tensor( [self.graph.nodes[n]["mask"] for n in self.graph.nodes], dtype=torch.float32) return Data(x=node_feature, edge_index=edge_index, edge_attr=edge_feature, root_feature=root_feature, mask=mask)
def setUp(self): self.G = nx.path_graph(9) self.DG = nx.path_graph(9, create_using=nx.DiGraph()) self.MG = nx.path_graph(9, create_using=nx.MultiGraph()) self.MDG = nx.path_graph(9, create_using=nx.MultiDiGraph()) self.Gv = nx.to_undirected(self.DG) self.DGv = nx.to_directed(self.G) self.MGv = nx.to_undirected(self.MDG) self.MDGv = nx.to_directed(self.MG) self.Rv = self.DG.reverse() self.MRv = self.MDG.reverse() self.graphs = [self.G, self.DG, self.MG, self.MDG, self.Gv, self.DGv, self.MGv, self.MDGv, self.Rv, self.MRv] for G in self.graphs: G.edges, G.nodes, G.degree
def test_draw_grid_model(self): layer_grid = create_empty_copy(nx.to_directed(nx.grid_2d_graph(5, 5))) for node in layer_grid.nodes.values(): node['layer'] = models_generation.random_layer() layer_grid.add_node('input') layer_grid.add_node('output_conv') layer_grid.nodes['output_conv']['layer'] = models_generation.IdentityLayer() layer_grid.nodes[(0,0)]['layer'] = ConvLayer(filter_num=50) layer_grid.nodes[(0,1)]['layer'] = ConvLayer(filter_num=50) layer_grid.nodes[(0,2)]['layer'] = DropoutLayer() layer_grid.add_edge('input', (0, 0)) layer_grid.add_edge((0, 5 - 1), 'output_conv') for i in range(5 - 1): layer_grid.add_edge((0, i), (0, i + 1)) layer_grid.graph['height'] = 5 layer_grid.graph['width'] = 5 if models_generation.check_legal_grid_model(layer_grid): print('legal model') else: print('illegal model') # model = models_generation.random_grid_model(10) layer_grid.add_edge((0,0), (0, 2)) real_model = models_generation.ModelFromGrid(layer_grid) # model = models_generation.random_model(10) # real_model = finalize_model(model) # for i in range(100): # add_random_connection(model) input_shape = (60, global_vars.get('eeg_chans'), global_vars.get('input_time_len'), 1) out = real_model(np_to_var(np.ones(input_shape, dtype=np.float32))) s = Source(make_dot(out), filename="test.gv", format="png") s.view()
def solve(ug, costs, pairs): g = nx.to_directed(ug) k, n, m = len(pairs), nx.number_of_nodes(g), nx.number_of_edges(g) N = len(costs) + n * k lp = lpsolve('make_lp', 0, N) lpsolve('set_obj_fn', lp, costs + [0] * n * k) sources = [s for (s, t) in p] zero = [0] * N constraint_coefficients = [0] * N for i, (u, v) in enumerate(g.edges()): constraint_coefficients[i] = 1 for j, s in enumerate(sources): constraint_coefficients[m + j * n + u] = -1 constraint_coefficients[m + j * n + v] = 1 lpsolve('add_constraint', lp, constraint_coefficients, 'GE', 0) constraint_coefficients[m + j * n + u] = 0 constraint_coefficients[m + j * n + v] = 0 constraint_coefficients[i] = 0 for j, (s, t) in enumerate(pairs): zero[m + j * n + s] = 1 lpsolve('add_constraint', lp, zero, 'EQ', 1) zero[m + j * n + s] = 0 zero[m + j * n + t] = 1 lpsolve('add_constraint', lp, zero, 'EQ', 0) zero[m + j * n + t] = 0 lpsolve('set_int', lp, [1] * N) lpsolve('set_lowbo', lp, [0] * N) lpsolve('set_verbose', lp, IMPORTANT) lpsolve('write_lp', lp, 'multicut_lpsolve.lp') lpsolve('solve', lp) val = lpsolve('get_variables', lp)[0][:m] return [e for i, e in enumerate(g.edges()) if val[i] == 1]
def save_graph(G, output_path, delimiter=',', write_stats=True, write_weights=False, write_dir=True): r""" Saves a graph to a file as an edgelist of weighted edgelist. If the stats parameter is set to True the file will include several lines containing the same basic graph statistics as provided by the get_stats function. For undirected graphs, the method stores both directions of every edge. Parameters ---------- G : graph A NetworkX graph output_path : file or string File or filename to write. If a file is provided, it must be opened in 'wb' mode. delimiter : string, optional The string used to separate values. Default is ','. write_stats : bool, optional Sets if graph statistics should be added to the edgelist or not. Default is True. write_weights : bool, optional If True data will be stored as weighted edgelist (e.g. triplets src, dst, weight) otherwise as normal edgelist. If the graph edges have no weight attribute and this parameter is set to True, a weight of 1 will be assigned to each edge. Default is False. write_dir : bool, optional This option is only relevant for undirected graphs. If False, the graph will be stored with a single direction of the edges. If True, both directions of edges will be stored. Default is True. """ # Write the graph stats in the file if required if write_stats: get_stats(G, output_path) # Open the file where data should be stored f = open(output_path, 'a+b') # Write the graph to a file and use both edge directions if graph is undirected if G.is_directed(): # Store edgelist if write_weights: J = nx.DiGraph() J.add_weighted_edges_from(G.edges.data('weight', 1)) nx.write_weighted_edgelist(J, f, delimiter=delimiter) else: nx.write_edgelist(G, f, delimiter=delimiter, data=False) else: if write_dir: H = nx.to_directed(G) J = nx.DiGraph() else: H = G J = nx.DiGraph() # Store edgelist if write_weights: J.add_weighted_edges_from(H.edges.data('weight', 1)) nx.write_weighted_edgelist(J, f, delimiter=delimiter) else: nx.write_edgelist(H, f, delimiter=delimiter, data=False)
def _read_graph(self, filename: Path): graph = nx.read_gpickle(filename) if isinstance(graph, nx.Graph): graph = nx.to_directed(graph) graph = nx.convert_node_labels_to_integers(graph, first_label=len( self._graph.nodes)) self._graph = nx.union(self._graph, graph)
def setUp(self): self.G = nx.path_graph(9) self.DG = nx.path_graph(9, create_using=nx.DiGraph()) self.MG = nx.path_graph(9, create_using=nx.MultiGraph()) self.MDG = nx.path_graph(9, create_using=nx.MultiDiGraph()) self.Gv = nx.to_undirected(self.DG) self.DGv = nx.to_directed(self.G) self.MGv = nx.to_undirected(self.MDG) self.MDGv = nx.to_directed(self.MG) self.Rv = self.DG.reverse() self.MRv = self.MDG.reverse() self.graphs = [ self.G, self.DG, self.MG, self.MDG, self.Gv, self.DGv, self.MGv, self.MDGv, self.Rv, self.MRv ] for G in self.graphs: G.edges, G.nodes, G.degree
def nx_to_openne_graph(nxgraph, stringify_nodes=True): dg = nx.to_directed(nxgraph).copy() if stringify_nodes: nx.relabel_nodes(dg, {n:str(n) for n in dg.nodes}, copy=False) nx.set_edge_attributes(dg, 1.0, 'weight') g = graph.Graph() g.G = dg g.encode_node() return g
def test_basic_load(db): for graph in testgraphs: if not graph.is_directed(): graph = nx.to_directed(graph) alleged = db.graph[graph.name] assert set(graph.nodes.keys()) == set(alleged.nodes.keys()), "{}'s nodes are not the same after load".format( graph.name ) assert set(graph.edges) == set(alleged.edges), "{}'s edges are not the same after load".format(graph.name)
def test_successors(self): g = nx.karate_club_graph() g1 = nx.to_directed(g) ag = AGraph(g1) n1 = ag.successors(1) g = from_nx_to_igraph(g1, directed=True) ag = AGraph(g) n2 = ag.successors(1) self.assertListEqual(n1, n2)
def create_knight_graph(side_length): G_knight = nx.Graph() knight_edge_list = create_knight_graph_edge_list(side_length) G_knight.add_edges_from(knight_edge_list) G_knight = nx.to_directed(G_knight) return G_knight
def fill_weights(self, Graph=None): if Graph: out = nx.to_directed(Graph) strecke = [k for k in Graph.edges.data('length')] for k in range(len(strecke)): list_strecke = list(strecke[k][:]) list_strecke[2] = round( np.exp(-(np.square(list_strecke[2])) / (2 * 100**2))) out.add_weighted_edges_from([tuple(list_strecke)]) return out else: out = nx.to_directed(self.Graph) strecke = [k for k in self.Graph.edges.data('length')] for k in range(len(strecke)): list_strecke = list(strecke[k][:]) list_strecke[2] = round( np.exp(-(np.square(list_strecke[2])) / (2 * 100**2))) out.add_weighted_edges_from([tuple(list_strecke)]) return out
def generate_graphs(num_voters, num_graphs, gtype='scale-free', seed=42, params=dict()): if 'clique_size' in params.keys(): assert num_voters % params[ 'clique_size'] == 0, f"Cliques must be of equal size: number of voters must be a multiple \ of clique_size size. Values passed: num_voters={num_voters}, clique_size={params['clique_size']}" gtypes = { 'scale-free': lambda: nx.DiGraph( nx.generators.random_graphs.barabasi_albert_graph( num_voters, 1, seed)), 'path': lambda: nx.DiGraph((nx.generators.classic.path_graph( num_voters, create_using=nx.classes.multidigraph.MultiDiGraph))), 'random': lambda: random_network(num_voters, params['prob'], seed=seed), 'regular': lambda: nx.to_directed( nx.generators.random_graphs.random_regular_graph( params['degree'], num_voters, seed)), 'small-world': lambda: nx.to_directed( nx.generators.random_graphs.watts_strogatz_graph( num_voters, params['degree'], params['prob'], seed)), 'caveman': lambda: nx.to_directed( nx.generators.community.connected_caveman_graph( num_voters // params['clique_size'], params['clique_size'])), } if gtype not in gtypes: raise NotImplementedError('This graph type has not been implemented.') g_func = gtypes[gtype] for i in range(num_graphs): seed = seed + 1 if seed is not None else None yield g_func()
def simpleCycleGraph(subset): n = len(subset) D = dict(zip(np.array([i for i in range(n)]), subset)) G = nx.cycle_graph(n) G = nx.to_directed(G) G = nx.relabel_nodes(G, D) ut.normalizeGraph(G) return G
def load(self, snapshot=False): self.offer_save() directory = self.SNAPSHOT_DIR if snapshot else self.SAVE_DIR self.print_bold('Load Session:') name = self.offer_choice(self.saved_sessions(directory)) if name: self.__init__() self.graph = nx.read_gml(directory + name) self.graph = nx.to_directed(self.graph) self.name = name print('loaded!') return name
def db(tmpdbfile): with ORM('sqlite:///' + tmpdbfile) as orm: for graph in testgraphs: orm.new_digraph(graph.name, graph) if not graph.is_directed(): graph = nx.to_directed(graph) assert set(graph.nodes.keys()) == set(orm.graph[graph.name].nodes.keys()), \ "{}'s nodes changed during instantiation".format(graph.name) assert set(graph.edges) == set(orm.graph[graph.name].edges.keys()), \ "{}'s edges changed during instantiation".format(graph.name) with ORM('sqlite:///' + tmpdbfile) as orm: yield orm
def __getitem__(self, idx): node_feature = torch.as_tensor( [self.data[n][3] for n in self.graph.nodes], dtype=torch.float32) g = nx.to_directed(self.graph) g = nx.convert_node_labels_to_integers(g) edge_index = torch.as_tensor([[x[0], x[1]] for x in g.edges], dtype=torch.long) edge_feature = torch.as_tensor( [g.edges[x[0], x[1]]["length"] for x in g.edges], dtype=torch.float32) return Data(x=node_feature, edge_index=edge_index, edge_attr=edge_feature)
def __init__(self, nodes, edges): """ ################################################### Declaration du reseau g (nodes et edges) ################################################### """ self.g = nx.to_directed( nx.fast_gnp_random_graph(nodes, edges / nodes, directed=True)) self.nodes = nodes self.node_pose = {} for i in self.g.nodes(): self.node_pose[i] = (random.uniform(1.0, 10.0), random.uniform(1.0, 10.0)) self.G = nx.DiGraph(self.g) for i, j in self.g.edges: if self.g.get_edge_data(j, i) == None: self.G.add_edge(j, i) self.g = self.G """ ################################################### Declaration des variables qui caracterise les nodes ################################################### """ self.color = {} self.dict_capa = {} self.dict_used = {} self.dict_ratio = {} self.dict_delay = {} """ ################################################### ################################################### """ self.list_keys = [ 'shortest_path', 'min_delay', 'min_banwidth_sum', 'min_banwidth_square_sum', 'min_score', 'min_square_score' ] self.dict_prob = {} self.opti_path = {} self.target_dict = defaultdict(dict)
def shortest_path_distances(A, source=None, target=None, reversed_directions=False, prenormalized_A=False): if not prenormalized_A: Adj = matrix_normalize(A, row_normalize=True) else: Adj = A Adj = np.array( 1 - Adj ) # Preliminary effective distance, converting edge weights from indicating proximity to distances for evaluation by shortest path Adj = np.where( Adj == 0, 1e-100, Adj ) # Replacing 0s by ~0s, so network remains connected for shortest path algorithm inverted_weights_nx_graph = to_directed( from_numpy_matrix(Adj, create_using=DiGraph)) if reversed_directions: inverted_weights_nx_graph = inverted_weights_nx_graph.reverse( copy=False) # SPD_dic = dict(nx.shortest_path_length(inverted_weights_nx_graph, source=source, target=target, weight='weight')) shortest_paths = shortest_path(inverted_weights_nx_graph, source=source, target=target, weight='weight') # if shortest_paths if source is None: if target is None: SPD = np.array([[ sum_weighted_path(Adj, shortest_paths[s][t]) for s in range(Adj.shape[0]) ] for t in range(Adj.shape[0])]) else: SPD = np.array([ sum_weighted_path(Adj, shortest_paths[s][target]) for s in range(Adj.shape[0]) ]) else: if target is None: SPD = np.array([ sum_weighted_path(Adj, shortest_paths[source][t]) for t in range(Adj.shape[0]) ]) else: SPD = sum_weighted_path(Adj, shortest_paths[source][target]) return SPD
def new_digraph(self, name, data=None, **attr): """Return a new instance of type DiGraph, initialized with the given data if provided. :arg name: a name for the graph :arg data: dictionary or NetworkX graph object providing initial state """ if data and isinstance(data, nx.Graph): if not data.is_directed(): data = nx.to_directed(data) self._init_graph(name, 'DiGraph', [data._node, data._succ, data.graph]) else: self._init_graph(name, 'DiGraph', data) return DiGraph(self, name)
def performance_generator(n: int): """ Creates a directed circular graph used to do the performance testing of the two algorithms which has the same number of nodes and edges :param n: the graph size :return: """ # must make a copy because the graph is frozen graph = nx.DiGraph(nx.to_directed(nx.path_graph(n))) edges_to_delete = list(zip(list(graph.nodes)[1:], list(graph.nodes)[:-1])) graph.remove_edges_from(edges_to_delete) graph.add_edge(max(graph.nodes), 0) nx.set_node_attributes(graph, 3, 'component_delay') nx.set_edge_attributes(graph, 1, 'wire_delay') path = os.getcwd() + '/../perf-graphs/' nx.nx_agraph.write_dot(graph, path + 'clean/perf-{}.dot'.format(str(n)))
def test_already_directed(self): dd = nx.to_directed(self.dv) Mdd = nx.to_directed(self.Mdv) assert_edges_equal(dd.edges, self.dv.edges) assert_edges_equal(Mdd.edges, self.Mdv.edges)
def setup(self): self.G = nx.path_graph(9) self.dv = nx.to_directed(self.G) self.MG = nx.path_graph(9, create_using=nx.MultiGraph()) self.Mdv = nx.to_directed(self.MG)
def test_already_directed(self): dd = nx.to_directed(self.dv) Mdd = nx.to_directed(self.Mdv)