def test_graph(self): g = nx.cycle_graph(10) G = nx.Graph() G.add_nodes_from(g) G.add_weighted_edges_from((u, v, u) for u, v in g.edges()) # Dict of dicts dod = to_dict_of_dicts(G) GG = from_dict_of_dicts(dod, create_using=nx.Graph()) assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes())) assert_edges_equal(sorted(G.edges()), sorted(GG.edges())) GW = to_networkx_graph(dod, create_using=nx.Graph()) assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes())) assert_edges_equal(sorted(G.edges()), sorted(GW.edges())) GI = nx.Graph(dod) assert_equal(sorted(G.nodes()), sorted(GI.nodes())) assert_equal(sorted(G.edges()), sorted(GI.edges())) # Dict of lists dol = to_dict_of_lists(G) GG = from_dict_of_lists(dol, create_using=nx.Graph()) # dict of lists throws away edge data so set it to none enone = [(u, v, {}) for (u, v, d) in G.edges(data=True)] assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes())) assert_edges_equal(enone, sorted(GG.edges(data=True))) GW = to_networkx_graph(dol, create_using=nx.Graph()) assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes())) assert_edges_equal(enone, sorted(GW.edges(data=True))) GI = nx.Graph(dol) assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes())) assert_edges_equal(enone, sorted(GI.edges(data=True)))
def test_graph(self): g = nx.cycle_graph(10) G = nx.Graph() G.add_nodes_from(g) G.add_weighted_edges_from((u, v, u) for u, v in g.edges()) # Dict of dicts dod = to_dict_of_dicts(G) GG = from_dict_of_dicts(dod, create_using=nx.Graph) assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes())) assert_edges_equal(sorted(G.edges()), sorted(GG.edges())) GW = to_networkx_graph(dod, create_using=nx.Graph) assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes())) assert_edges_equal(sorted(G.edges()), sorted(GW.edges())) GI = nx.Graph(dod) assert sorted(G.nodes()) == sorted(GI.nodes()) assert sorted(G.edges()) == sorted(GI.edges()) # Dict of lists dol = to_dict_of_lists(G) GG = from_dict_of_lists(dol, create_using=nx.Graph) # dict of lists throws away edge data so set it to none enone = [(u, v, {}) for (u, v, d) in G.edges(data=True)] assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes())) assert_edges_equal(enone, sorted(GG.edges(data=True))) GW = to_networkx_graph(dol, create_using=nx.Graph) assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes())) assert_edges_equal(enone, sorted(GW.edges(data=True))) GI = nx.Graph(dol) assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes())) assert_edges_equal(enone, sorted(GI.edges(data=True)))
def random_del_graph(adj, seed): G = nx.from_numpy_matrix(adj) np.random.seed(seed) node_order = list(G.nodes) node_order_r = np.random.permutation(node_order) new_order_graph = dict() for node in node_order_r: new_order_graph.update({node: G[node]}) new_order_graph = from_dict_of_dicts(new_order_graph, create_using=Graph) new_object_matrix = nx.adjacency_matrix(new_order_graph).todense() return node_order, node_order_r, new_object_matrix
def random_del_graph(adj, seed, data_type='voter'): if data_type == 'cml': G = nx.from_numpy_matrix(adj.cpu().data.numpy()) if data_type == 'voter': G = nx.from_numpy_matrix(adj) np.random.seed(seed) node_order = list(G.nodes) node_order_r = np.random.permutation(node_order) new_order_graph = dict() for node in node_order_r: new_order_graph.update({node: G[node]}) new_order_graph = from_dict_of_dicts(new_order_graph, create_using=Graph) new_object_matrix = torch.FloatTensor( nx.adjacency_matrix(new_order_graph).todense()).cuda() return node_order, node_order_r, new_object_matrix
def test_with_multiedges_self_loops(self): G = cycle_graph(10) XG = nx.Graph() XG.add_nodes_from(G) XG.add_weighted_edges_from((u, v, u) for u, v in G.edges()) XGM = nx.MultiGraph() XGM.add_nodes_from(G) XGM.add_weighted_edges_from((u, v, u) for u, v in G.edges()) XGM.add_edge(0, 1, weight=2) # multiedge XGS = nx.Graph() XGS.add_nodes_from(G) XGS.add_weighted_edges_from((u, v, u) for u, v in G.edges()) XGS.add_edge(0, 0, weight=100) # self loop # Dict of dicts # with self loops, OK dod = to_dict_of_dicts(XGS) GG = from_dict_of_dicts(dod, create_using=nx.Graph) assert_nodes_equal(XGS.nodes(), GG.nodes()) assert_edges_equal(XGS.edges(), GG.edges()) GW = to_networkx_graph(dod, create_using=nx.Graph) assert_nodes_equal(XGS.nodes(), GW.nodes()) assert_edges_equal(XGS.edges(), GW.edges()) GI = nx.Graph(dod) assert_nodes_equal(XGS.nodes(), GI.nodes()) assert_edges_equal(XGS.edges(), GI.edges()) # Dict of lists # with self loops, OK dol = to_dict_of_lists(XGS) GG = from_dict_of_lists(dol, create_using=nx.Graph) # dict of lists throws away edge data so set it to none enone = [(u, v, {}) for (u, v, d) in XGS.edges(data=True)] assert_nodes_equal(sorted(XGS.nodes()), sorted(GG.nodes())) assert_edges_equal(enone, sorted(GG.edges(data=True))) GW = to_networkx_graph(dol, create_using=nx.Graph) assert_nodes_equal(sorted(XGS.nodes()), sorted(GW.nodes())) assert_edges_equal(enone, sorted(GW.edges(data=True))) GI = nx.Graph(dol) assert_nodes_equal(sorted(XGS.nodes()), sorted(GI.nodes())) assert_edges_equal(enone, sorted(GI.edges(data=True))) # Dict of dicts # with multiedges, OK dod = to_dict_of_dicts(XGM) GG = from_dict_of_dicts(dod, create_using=nx.MultiGraph, multigraph_input=True) assert_nodes_equal(sorted(XGM.nodes()), sorted(GG.nodes())) assert_edges_equal(sorted(XGM.edges()), sorted(GG.edges())) GW = to_networkx_graph(dod, create_using=nx.MultiGraph, multigraph_input=True) assert_nodes_equal(sorted(XGM.nodes()), sorted(GW.nodes())) assert_edges_equal(sorted(XGM.edges()), sorted(GW.edges())) GI = nx.MultiGraph( dod) # convert can't tell whether to duplicate edges! assert_nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes())) # assert_not_equal(sorted(XGM.edges()), sorted(GI.edges())) assert not sorted(XGM.edges()) == sorted(GI.edges()) GE = from_dict_of_dicts(dod, create_using=nx.MultiGraph, multigraph_input=False) assert_nodes_equal(sorted(XGM.nodes()), sorted(GE.nodes())) assert sorted(XGM.edges()) != sorted(GE.edges()) GI = nx.MultiGraph(XGM) assert_nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes())) assert_edges_equal(sorted(XGM.edges()), sorted(GI.edges())) GM = nx.MultiGraph(G) assert_nodes_equal(sorted(GM.nodes()), sorted(G.nodes())) assert_edges_equal(sorted(GM.edges()), sorted(G.edges())) # Dict of lists # with multiedges, OK, but better write as DiGraph else you'll # get double edges dol = to_dict_of_lists(G) GG = from_dict_of_lists(dol, create_using=nx.MultiGraph) assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes())) assert_edges_equal(sorted(G.edges()), sorted(GG.edges())) GW = to_networkx_graph(dol, create_using=nx.MultiGraph) assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes())) assert_edges_equal(sorted(G.edges()), sorted(GW.edges())) GI = nx.MultiGraph(dol) assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes())) assert_edges_equal(sorted(G.edges()), sorted(GI.edges()))
def test_with_multiedges_self_loops(self): G = cycle_graph(10) XG = nx.Graph() XG.add_nodes_from(G) XG.add_weighted_edges_from((u, v, u) for u, v in G.edges()) XGM = nx.MultiGraph() XGM.add_nodes_from(G) XGM.add_weighted_edges_from((u, v, u) for u, v in G.edges()) XGM.add_edge(0, 1, weight=2) # multiedge XGS = nx.Graph() XGS.add_nodes_from(G) XGS.add_weighted_edges_from((u, v, u) for u, v in G.edges()) XGS.add_edge(0, 0, weight=100) # self loop # Dict of dicts # with self loops, OK dod = to_dict_of_dicts(XGS) GG = from_dict_of_dicts(dod, create_using=nx.Graph()) assert_nodes_equal(XGS.nodes(), GG.nodes()) assert_edges_equal(XGS.edges(), GG.edges()) GW = to_networkx_graph(dod, create_using=nx.Graph()) assert_nodes_equal(XGS.nodes(), GW.nodes()) assert_edges_equal(XGS.edges(), GW.edges()) GI = nx.Graph(dod) assert_nodes_equal(XGS.nodes(), GI.nodes()) assert_edges_equal(XGS.edges(), GI.edges()) # Dict of lists # with self loops, OK dol = to_dict_of_lists(XGS) GG = from_dict_of_lists(dol, create_using=nx.Graph()) # dict of lists throws away edge data so set it to none enone = [(u, v, {}) for (u, v, d) in XGS.edges(data=True)] assert_nodes_equal(sorted(XGS.nodes()), sorted(GG.nodes())) assert_edges_equal(enone, sorted(GG.edges(data=True))) GW = to_networkx_graph(dol, create_using=nx.Graph()) assert_nodes_equal(sorted(XGS.nodes()), sorted(GW.nodes())) assert_edges_equal(enone, sorted(GW.edges(data=True))) GI = nx.Graph(dol) assert_nodes_equal(sorted(XGS.nodes()), sorted(GI.nodes())) assert_edges_equal(enone, sorted(GI.edges(data=True))) # Dict of dicts # with multiedges, OK dod = to_dict_of_dicts(XGM) GG = from_dict_of_dicts(dod, create_using=nx.MultiGraph(), multigraph_input=True) assert_nodes_equal(sorted(XGM.nodes()), sorted(GG.nodes())) assert_edges_equal(sorted(XGM.edges()), sorted(GG.edges())) GW = to_networkx_graph(dod, create_using=nx.MultiGraph(), multigraph_input=True) assert_nodes_equal(sorted(XGM.nodes()), sorted(GW.nodes())) assert_edges_equal(sorted(XGM.edges()), sorted(GW.edges())) GI = nx.MultiGraph(dod) # convert can't tell whether to duplicate edges! assert_nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes())) #assert_not_equal(sorted(XGM.edges()), sorted(GI.edges())) assert_false(sorted(XGM.edges()) == sorted(GI.edges())) GE = from_dict_of_dicts(dod, create_using=nx.MultiGraph(), multigraph_input=False) assert_nodes_equal(sorted(XGM.nodes()), sorted(GE.nodes())) assert_not_equal(sorted(XGM.edges()), sorted(GE.edges())) GI = nx.MultiGraph(XGM) assert_nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes())) assert_edges_equal(sorted(XGM.edges()), sorted(GI.edges())) GM = nx.MultiGraph(G) assert_nodes_equal(sorted(GM.nodes()), sorted(G.nodes())) assert_edges_equal(sorted(GM.edges()), sorted(G.edges())) # Dict of lists # with multiedges, OK, but better write as DiGraph else you'll # get double edges dol = to_dict_of_lists(G) GG = from_dict_of_lists(dol, create_using=nx.MultiGraph()) assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes())) assert_edges_equal(sorted(G.edges()), sorted(GG.edges())) GW = to_networkx_graph(dol, create_using=nx.MultiGraph()) assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes())) assert_edges_equal(sorted(G.edges()), sorted(GW.edges())) GI = nx.MultiGraph(dol) assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes())) assert_edges_equal(sorted(G.edges()), sorted(GI.edges()))
def to_nx_graph(data, create_using=None, multigraph_input=False): # noqa: C901 """Make a graph from a known data structure. The preferred way to call this is automatically from the class constructor >>> d = {0: {1: {'weight':1}}} # dict-of-dicts single edge (0,1) >>> G = nx.Graph(d) instead of the equivalent >>> G = nx.from_dict_of_dicts(d) Parameters ---------- data : object to be converted Current known types are: any NetworkX graph dict-of-dicts dict-of-lists container (ie set, list, tuple, iterator) of edges Pandas DataFrame (row per edge) numpy matrix numpy ndarray scipy sparse matrix create_using : nx graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. multigraph_input : bool (default False) If True and data is a dict_of_dicts, try to create a multigraph assuming dict_of_dict_of_lists. If data and create_using are both multigraphs then create a multigraph from a multigraph. """ # networkx graph or graphscope.nx graph if hasattr(data, "adj"): try: result = from_dict_of_dicts( data.adj, create_using=create_using, multigraph_input=data.is_multigraph(), ) if hasattr(data, "graph"): # data.graph should be dict-like result.graph.update(data.graph) if hasattr(data, "nodes"): # data.nodes should be dict-like result.add_nodes_from(data.nodes.items()) return result except Exception as e: raise nx.NetworkXError( "Input is not a correct NetworkX-like graph.") from e # dict of dicts/lists if isinstance(data, dict): try: return from_dict_of_dicts(data, create_using=create_using, multigraph_input=multigraph_input) except Exception: try: return from_dict_of_lists(data, create_using=create_using) except Exception as e: raise TypeError("Input is not known type.") from e # list or generator of edges if isinstance(data, (list, tuple)) or any( hasattr(data, attr) for attr in ["_adjdict", "next", "__next__"]): try: return from_edgelist(data, create_using=create_using) except Exception as e: raise nx.NetworkXError("Input is not a valid edge list") from e # Pandas DataFrame try: import pandas as pd if isinstance(data, pd.DataFrame): if data.shape[0] == data.shape[1]: try: return nx.from_pandas_adjacency(data, create_using=create_using) except Exception as e: msg = "Input is not a correct Pandas DataFrame adjacency matrix." raise nx.NetworkXError(msg) from e else: try: return nx.from_pandas_edgelist(data, edge_attr=True, create_using=create_using) except Exception as e: msg = "Input is not a correct Pandas DataFrame edge-list." raise nx.NetworkXError(msg) from e except ImportError: msg = "pandas not found, skipping conversion test." warnings.warn(msg, ImportWarning) # numpy matrix or ndarray try: import numpy if isinstance(data, (numpy.matrix, numpy.ndarray)): try: return nx.from_numpy_matrix(data, create_using=create_using) except Exception as e: raise nx.NetworkXError( "Input is not a correct numpy matrix or array.") from e except ImportError: warnings.warn("numpy not found, skipping conversion test.", ImportWarning) # scipy sparse matrix - any format try: import scipy if hasattr(data, "format"): try: return nx.from_scipy_sparse_matrix(data, create_using=create_using) except Exception as e: raise nx.NetworkXError( "Input is not a correct scipy sparse matrix type.") from e except ImportError: warnings.warn("scipy not found, skipping conversion test.", ImportWarning) raise nx.NetworkXError("Input is not a known data type for conversion.")
def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr): """Initialize a graph with edges, name, or graph attributes. Parameters ---------- incoming_graph_data : input graph Data to initialize graph. If incoming_graph_data=None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph. multigraph_input : bool or None (default None) Note: Only used when `incoming_graph_data` is a dict. If True, `incoming_graph_data` is assumed to be a dict-of-dict-of-dict-of-dict structure keyed by node to neighbor to edge keys to edge data for multi-edges. A NetworkXError is raised if this is not the case. If False, :func:`to_networkx_graph` is used to try to determine the dict's graph data structure as either a dict-of-dict-of-dict keyed by node to neighbor to edge data, or a dict-of-iterable keyed by node to neighbors. If None, the treatment for True is tried, but if it fails, the treatment for False is tried. attr : keyword arguments, optional (default= no attributes) Attributes to add to graph as key=value pairs. See Also -------- convert Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G = nx.Graph(name="my graph") >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges >>> G = nx.Graph(e) Arbitrary graph attribute pairs (key=value) may be assigned >>> G = nx.Graph(e, day="Friday") >>> G.graph {'day': 'Friday'} """ self.edge_key_dict_factory = self.edge_key_dict_factory # multigraph_input can be None/True/False. So check "is not False" if isinstance(incoming_graph_data, dict) and multigraph_input is not False: DiGraph.__init__(self) try: convert.from_dict_of_dicts(incoming_graph_data, create_using=self, multigraph_input=True) self.graph.update(attr) except Exception as e: if multigraph_input is True: raise nx.NetworkXError( f"converting multigraph_input raised:\n{type(e)}: {e}") DiGraph.__init__(self, incoming_graph_data, **attr) else: DiGraph.__init__(self, incoming_graph_data, **attr)
def shuffle_graph(data_graph: NetworkXGraphObject, seed: Optional[int] = None, prng_type: str = default_prng_type) -> NetworkXGraphObject: ''' Returns a new graph, shuffling the order of the nodes in the input data_graph, but the relationship between the nodes remains the same. The data_graph doesn't change. Parameters ---------- data_graph: NetworkXGraphObject A NetworkX graph object. seed: int, default None The seed of a pseudo-random number generator. prng_type: str, default default_prng_type Specifies the pseudo-random number generator algorithm to use. Returns ------- new_order_data_graph: NetworkXGraphObject Returns a new graph that shuffles the order of nodes but keeps the relationships between them the same. Examples -------- >>> from networkx.classes.graph import Graph >>> G = Graph({0: {1: {}}, 1: {0: {}, 2: {}}, 2: {1: {}, 3: {}}, 3: {2: {}, 4: {}}, 4: {3: {}}}) >>> seed = 170141183460469231731687303715884105727 >>> shuffle_graph(G, seed).adj #Set seed to make the results repeatable. AdjacencyView({1: {0: {}, 2: {}}, 2: {1: {}, 3: {}}, 3: {2: {}, 4: {}}, 4: {3: {}}, 0: {1: {}}}) ''' assert isinstance( data_graph, (Graph, DiGraph, MultiGraph, MultiDiGraph) ), f'data_graph must be an NetworkXGraphObject, got type {type(data_graph).__name__}' assert isinstance( seed, (int, type(None) )), f'seed must be an int or None, got type {type(seed).__name__}' assert isinstance( prng_type, str), f'prng_type must be an str, got type {type(prng_type).__name__}' if isinstance(seed, int) and (seed < 0): raise ValueError('seed must be >= 0') if prng_type not in prng_type_tuple: raise ValueError( 'The string for prng_type is not in the list of implemented algorithms.' ) from networkx.convert import from_dict_of_dicts list_of_nodes = list(data_graph.nodes) pr_complete_shuffle(list_of_nodes, seed, prng_type) new_order_data_graph = dict() for node in list_of_nodes: new_order_data_graph.update({node: data_graph[node]}) if data_graph.is_directed(): if data_graph.is_multigraph(): new_order_data_graph = from_dict_of_dicts( new_order_data_graph, create_using=MultiDiGraph, multigraph_input=True) else: new_order_data_graph = from_dict_of_dicts(new_order_data_graph, create_using=DiGraph) else: if data_graph.is_multigraph(): new_order_data_graph = from_dict_of_dicts(new_order_data_graph, create_using=MultiGraph, multigraph_input=True) else: new_order_data_graph = from_dict_of_dicts(new_order_data_graph, create_using=Graph) return new_order_data_graph