Python networkx.Graph() Examples

The following are 30 code examples of networkx.Graph(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: 20newsgroup.py    From OpenNE with MIT License 9 votes vote down vote up
def text_to_graph(text):
    import networkx as nx
    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.neighbors import kneighbors_graph

    # use tfidf to transform texts into feature vectors
    vectorizer = TfidfVectorizer()
    vectors = vectorizer.fit_transform(text)

    # build the graph which is full-connected
    N = vectors.shape[0]
    mat = kneighbors_graph(vectors, N, metric='cosine', mode='distance', include_self=True)
    mat.data = 1 - mat.data  # to similarity

    g = nx.from_scipy_sparse_matrix(mat, create_using=nx.Graph())

    return g 
Example #2
Source File: dataset_utils.py    From rl_graph_generation with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def mol_to_nx(mol):
    G = nx.Graph()

    for atom in mol.GetAtoms():
        G.add_node(atom.GetIdx(),
                   symbol=atom.GetSymbol(),
                   formal_charge=atom.GetFormalCharge(),
                   implicit_valence=atom.GetImplicitValence(),
                   ring_atom=atom.IsInRing(),
                   degree=atom.GetDegree(),
                   hybridization=atom.GetHybridization())
    for bond in mol.GetBonds():
        G.add_edge(bond.GetBeginAtomIdx(),
                   bond.GetEndAtomIdx(),
                   bond_type=bond.GetBondType())
    return G 
Example #3
Source File: tests.py    From networkx_viewer with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        # Create the graph for testing
        G = nx.Graph()
        G.add_edge('a',2)
        G.add_edge(2,'c')
        G.add_edge('a','c')
        G.add_edge('a',4)
        G.add_edge(4,'c')
        G.add_edge('out','c')
        G.add_edge('c','d')
        G.add_edge('d',2)
        # Growth edges
        G.add_edge('out',11)
        G.add_edge('out',12)
        G.add_edge(12, 'd')
        G.add_edge('TTTTT',11)
        G.add_edge('qqqq', 'TTTTT')
        G.add_node('alone')
        self.input_G = G.copy()

        # Viewer under test
        self.a = nxv.GraphCanvas(G) 
Example #4
Source File: graph_canvas.py    From networkx_viewer with GNU General Public License v3.0 6 votes vote down vote up
def _radial_behind(self, home_node, behind_node):
        """Detect what nodes create a radial string behind the edge from
        home_node to behind_node"""

        base_islands = nx.number_connected_components(self.dispG)

        # If we remove the edge in question, it should radialize the system
        #  and we can then detect the side to remove
        G = nx.Graph()
        G.add_nodes_from(self.dispG.nodes())
        G.add_edges_from(self.dispG.edges())
        G.remove_edge(home_node, behind_node)

        node_sets = list(nx.connected_components(G))

        if len(node_sets) == base_islands:
            # There is no radial path behind this node
            return None
        else:
            for ns in node_sets:
                if behind_node in ns:
                    # We know know what nodes to remove from the display graph
                    #  to remove the radial string
                    return ns 
Example #5
Source File: comment_tree.py    From news-popularity-prediction with Apache License 2.0 6 votes vote down vote up
def calculate_max_depth_over_max_width(comment_tree):
    comment_tree_nx = nx.from_scipy_sparse_matrix(comment_tree, create_using=nx.Graph())

    if len(comment_tree_nx) == 0:
        max_depth_over_max_width = 0.0
    else:
        node_to_depth = nx.shortest_path_length(comment_tree_nx, 0)
        depth_to_nodecount = collections.defaultdict(int)

        for k, v in node_to_depth.items():
            depth_to_nodecount[v] += 1

        max_depth = max(node_to_depth.values())
        max_width = max(depth_to_nodecount.values())

        max_depth_over_max_width = max_depth/max_width

    return max_depth_over_max_width 
Example #6
Source File: graph_utils.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def convert_to_graph_tool(G):
  timer = utils.Timer()
  timer.tic()
  gtG = gt.Graph(directed=G.is_directed())
  gtG.ep['action'] = gtG.new_edge_property('int')

  nodes_list = G.nodes()
  nodes_array = np.array(nodes_list)

  nodes_id = np.zeros((nodes_array.shape[0],), dtype=np.int64)

  for i in range(nodes_array.shape[0]):
    v = gtG.add_vertex()
    nodes_id[i] = int(v)

  # d = {key: value for (key, value) in zip(nodes_list, nodes_id)}
  d = dict(itertools.izip(nodes_list, nodes_id))

  for src, dst, data in G.edges_iter(data=True):
    e = gtG.add_edge(d[src], d[dst])
    gtG.ep['action'][e] = data['action']
  nodes_to_id = d
  timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool')
  return gtG, nodes_array, nodes_to_id 
Example #7
Source File: comment_tree.py    From news-popularity-prediction with Apache License 2.0 6 votes vote down vote up
def calculate_comment_tree_hirsch(comment_tree):
    comment_tree_nx = nx.from_scipy_sparse_matrix(comment_tree, create_using=nx.Graph())

    if len(comment_tree_nx) == 0:
        comment_tree_hirsch = 0.0
    else:
        node_to_depth = nx.shortest_path_length(comment_tree_nx, 0)

        depth_to_nodecount = collections.defaultdict(int)

        for k, v in node_to_depth.items():
            depth_to_nodecount[v] += 1

        comment_tree_hirsch = max(node_to_depth.values())
        while True:
            if depth_to_nodecount[comment_tree_hirsch] >= comment_tree_hirsch:
                break
            else:
                comment_tree_hirsch -= 1

    return comment_tree_hirsch 
Example #8
Source File: pdbqt_utils.py    From deepchem with MIT License 6 votes vote down vote up
def mol_to_graph(mol):
  """Convert RDKit Mol to NetworkX graph

  Convert mol into a graph representation atoms are nodes, and bonds
  are vertices stored as graph

  Parameters
  ----------
  mol: rdkit Mol
    The molecule to convert into a graph. 

  Returns
  -------
  graph: networkx.Graph
    Contains atoms indices as nodes, edges as bonds.
  """
  import networkx as nx
  G = nx.Graph()
  num_atoms = mol.GetNumAtoms()
  G.add_nodes_from(range(num_atoms))
  for i in range(mol.GetNumBonds()):
    from_idx = mol.GetBonds()[i].GetBeginAtomIdx()
    to_idx = mol.GetBonds()[i].GetEndAtomIdx()
    G.add_edge(from_idx, to_idx)
  return G 
Example #9
Source File: main.py    From cd-diagram with GNU General Public License v3.0 6 votes vote down vote up
def form_cliques(p_values, nnames):
    """
    This method forms the cliques
    """
    # first form the numpy matrix data
    m = len(nnames)
    g_data = np.zeros((m, m), dtype=np.int64)
    for p in p_values:
        if p[3] == False:
            i = np.where(nnames == p[0])[0][0]
            j = np.where(nnames == p[1])[0][0]
            min_i = min(i, j)
            max_j = max(i, j)
            g_data[min_i, max_j] = 1

    g = networkx.Graph(g_data)
    return networkx.find_cliques(g) 
Example #10
Source File: object_utils.py    From ffn with Apache License 2.0 6 votes vote down vote up
def load_equivalences(paths):
  """Loads equivalences from a text file.

  Args:
    paths: sequence of paths to the text files of equivalences; id0,id1 per
      line, or id0,id1,x,y,z.

  Returns:
    NX graph object representing the equivalences
  """
  equiv_graph = nx.Graph()

  for path in paths:
    with open(path, "r") as f:
      reader = pd.read_csv(
          f, sep=",", engine="c", comment="#", chunksize=4096, header=None)
      for chunk in reader:
        if len(chunk.columns) not in (2, 5):
          logging.critical("Unexpected # of columns (%d), want 2 or 5",
                           len(chunk.columns))

        edges = chunk.values[:, :2]
        equiv_graph.add_edges_from(edges)

  return equiv_graph 
Example #11
Source File: test_dusc_path.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_no_cheapest_neighbor_first():
    # Example demonstrating that we should not always visit the cheapest
    # neighbor first
    # Visit order should be
    # C B F D E
    global G
    G = nx.Graph()
    G.add_edge('A', 'B', cost=3)
    G.add_edge('A', 'C', cost=1)
    G.add_edge('B', 'F', cost=1)
    G.add_edge('C', 'E', cost=5)
    G.add_edge('C', 'D', cost=4)
    visited = init('A')

    print('Visited : ',  visited)

    assert visited == ['A', 'C', 'B', 'F', 'D', 'E']
    print('\n\n') 
Example #12
Source File: test_dusc_path.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_one_loop_2():
    global G
    G = nx.Graph()
    G.add_edge('A', 'B', cost=2)
    G.add_edge('B', 'C', cost=1)
    G.add_edge('B', 'D', cost=2)
    G.add_edge('C', 'E', cost=2)
    G.add_edge('D', 'E', cost=2)
    G.add_edge('E', 'F', cost=5)
    G.add_edge('D', 'G', cost=1)
    visited = init('A')
    print('Visited : ',  visited)

    # order between E and G does not matter, the cost of the path from A to
    # them is the same (5)
    assert visited == ['A', 'B', 'C', 'D', 'E', 'G', 'F'] or \
        visited == ['A', 'B', 'C', 'D', 'G', 'E', 'F']
    print('\n\n') 
Example #13
Source File: env.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def __init_unrestorables(self):
        # anything that can't be restored from JSON file init here
        pop_name = ""
        if self.model_nm:
            pop_name += self.model_nm + " "
        pop_name += "Agents"
        self.agents = ap.AgentPop(pop_name)

        self.womb = []
        self.graph = nx.Graph()
        self.graph.add_edge(self, self.agents)
        if self.props is not None:
            self.graph.add_edge(self, self.props)
        self.graph.add_edge(self, self.user)
        self.graph.add_edge(self, self.menu)
        self.graph.add_edge(self, node.universals) 
Example #14
Source File: graph_utils.py    From metal with Apache License 2.0 6 votes vote down vote up
def get_clique_tree(nodes, edges):
    """Given a set of int nodes i and edges (i,j), returns an nx.Graph object G
    which is a clique tree, where:
        - G.node[i]['members'] contains the set of original nodes in the ith
            maximal clique
        - G[i][j]['members'] contains the set of original nodes in the seperator
            set between maximal cliques i and j

    Note: This method is currently only implemented for chordal graphs; TODO:
    add a step to triangulate non-chordal graphs.
    """
    # Form the original graph G1
    G1 = nx.Graph()
    G1.add_nodes_from(nodes)
    G1.add_edges_from(edges)

    # Check if graph is chordal
    # TODO: Add step to triangulate graph if not
    if not nx.is_chordal(G1):
        raise NotImplementedError("Graph triangulation not implemented.")

    # Create maximal clique graph G2
    # Each node is a maximal clique C_i
    # Let w = |C_i \cap C_j|; C_i, C_j have an edge with weight w if w > 0
    G2 = nx.Graph()
    for i, c in enumerate(nx.chordal_graph_cliques(G1)):
        G2.add_node(i, members=c)
    for i in G2.nodes:
        for j in G2.nodes:
            S = G2.node[i]["members"].intersection(G2.node[j]["members"])
            w = len(S)
            if w > 0:
                G2.add_edge(i, j, weight=w, members=S)

    # Return a minimum spanning tree of G2
    return nx.minimum_spanning_tree(G2) 
Example #15
Source File: utils.py    From PokemonGo-Bot with MIT License 6 votes vote down vote up
def find_biggest_cluster(radius, points, order=None):
    graph = nx.Graph()
    for point in points:
            if order is '9QM=':
                #is a lure module - 9QM=
                now = int(time.time())
                remaining = now - point['last_modified_timestamp_ms']
                f = point['latitude'], point['longitude'], remaining
            else:
                f = point['latitude'], point['longitude'], 0
            graph.add_node(f)
            for node in graph.nodes():
                if node != f and distance(f[0], f[1], node[0], node[1]) <= radius*2:
                    graph.add_edge(f, node)
    cliques = list(find_cliques(graph))
    if len(cliques) > 0:
        max_clique = max(list(find_cliques(graph)), key=lambda l: (len(l), sum(x[2] for x in l)))
        merc_clique = [coord2merc(x[0], x[1]) for x in max_clique]
        clique_x, clique_y = zip(*merc_clique)
        best_point = np.mean(clique_x), np.mean(clique_y)
        best_coord = merc2coord(best_point)
        return {'latitude': best_coord[0], 'longitude': best_coord[1], 'num_points': len(max_clique)}
    else:
        return None 
Example #16
Source File: graphs.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def as_networkx_bipartite_graph(variables, relations):
    """
    Build a networkx graph object from variables and relations.

    Parameters
    ----------
    variables: list
        a list of Variable objets
    relations: list
        a list of Relation objects

    Returns
    -------
    a networkx graph object
    """
    graph = nx.Graph()

    # One node for each variables
    graph.add_nodes_from([v.name for v in variables], bipartite=0)
    graph.add_nodes_from([r.name for r in relations], bipartite=1)

    for r in relations:
        for e in r.dimensions:
            graph.add_edge(r.name, e.name)
    return graph 
Example #17
Source File: graphs.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def as_networkx_graph(variables, relations):
    """
    Build a networkx graph object from variables and relations.

    Parameters
    ----------
    variables: list
        a list of Variable objets
    relations: list
        a list of Relation objects

    Returns
    -------
    a networkx graph object
    """
    graph = nx.Graph()

    # One node for each variables
    graph.add_nodes_from([v.name for v in variables])

    for r in relations:
        for p in all_pairs([e.name for e in r.dimensions]):
            graph.add_edge(*p)
    return graph 
Example #18
Source File: ising.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_binary_constraints(
    grid_graph: nx.Graph, variables, bin_range: float, extensive: bool
) -> Dict[str, Constraint]:
    constraints: Dict[str, Constraint] = {}
    for nodes in grid_graph.edges:
        (r1, c1), (r2, c2) = sorted(nodes)
        name1 = f"v_{r1}_{c1}"
        name2 = f"v_{r2}_{c2}"
        v1 = variables[name1]
        v2 = variables[name2]

        if extensive:
            constraint = generate_binary_extensive_constraint(v1, v2, bin_range)
        else:
            constraint = generate_binary_intentional_constraint(v1, v2, bin_range)
        constraints[constraint.name] = constraint
    return constraints 
Example #19
Source File: graphcoloring.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_scalefree_graph(variables_count, m_edge, allow_subgraph):
    if not allow_subgraph:
        graph = nx.barabasi_albert_graph(variables_count, m_edge)
        is_connected = nx.is_connected(graph)
        while not is_connected:
            graph = nx.barabasi_albert_graph(variables_count, m_edge)
            is_connected = nx.is_connected(graph)
    else:
        graph = nx.barabasi_albert_graph(variables_count, m_edge)

    # In the obtained graph, low rank nodes will have a much higher edge count
    # than high rank nodes. We shuffle the nodes names to avoid this effect:
    new_nodes = list(range(variables_count))
    random.shuffle(new_nodes)
    node_mapping = {n: nn for n, nn in zip(graph.nodes, new_nodes)}

    new_graph = nx.Graph((node_mapping[e1], node_mapping[e2]) for e1, e2 in graph.edges)
    return new_graph 
Example #20
Source File: preprocess.py    From EvalNE with MIT License 5 votes vote down vote up
def load_graph(input_path, delimiter=',', comments='#', directed=False):
    r"""
    Loads a directed or undirected graph from an edgelist. If the edgelist is weighted the provided graph will
    maintain those weights. For undirected graphs edges are sorted (smallID, bigID)
    
    Parameters
    ----------
    input_path : file or string
       File or filename to read.
    delimiter : string, optional
       The string used to separate values. Default is ','.
    comments : string, optional
       The character used to indicate the start of a comment. Default is '#'.
    directed : bool
       Indicated if the graph is directed or undirected.
    
    Returns
    -------
    G : graph
       A NetworkX graph
    """
    # Load edgelist
    E = np.loadtxt(input_path, delimiter=delimiter, comments=comments, dtype=int)

    # Create graph from the edgelist
    if directed:
        G = nx.DiGraph()
    else:
        # Make sure edges are sorted (smallNodeID, bigNodeID) for undirected graphs
        E.sort(axis=1)
        G = nx.Graph()

    if E.shape[1] == 2:
        # Create an unweighted graph
        G.add_edges_from(E)
    else:
        # Create an weighted graph
        G.add_weighted_edges_from(E[:, :3])

    # Return the nx graph
    return G 
Example #21
Source File: agent_pop.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def jsondump(self, obj):
        if type(obj) == nx.Graph:
            return "Graph"
        elif isinstance(obj, ent.Entity):
            return obj.to_json()
        else:
            return obj.__dict__ 
Example #22
Source File: networks.py    From minicps with MIT License 5 votes vote down vote up
def build_nx_graph():

    """Create a networkx graph.

    The graph contains two PLCs connected to a switch
    """

    graph = nx.Graph(name='test')

    links = 0

    s1 = DumbSwitch('s1')
    graph.add_node('s1', attr_dict=s1.get_params())

    plc1 = PLC('plc1', '192.168.1.10')
    graph.add_node('plc1', attr_dict=plc1.get_params())

    link = EthLink(label=links, bandwidth=30, delay=0, loss=0)
    graph.add_edge('plc1', 's1', attr_dict=link.get_params())
    links += 1

    plc2 = PLC('plc2', '192.168.1.20')
    graph.add_node('plc2', attr_dict=plc2.get_params())

    link = EthLink(label=links, bandwidth=30, delay=0, loss=0)
    graph.add_edge('plc2', 's1', attr_dict=link.get_params())
    links += 1

    return graph 
Example #23
Source File: exportnx.py    From GraphiPy with MIT License 5 votes vote down vote up
def create_from_neo4j(self, neo_graph, nx_graph=None, directional=False):
        nodes = neo_graph.get_nodes()
        edges = neo_graph.get_edges()

        if nx_graph is None:
            if directional:
                nx_graph = nx.DiGraph()
            else:
                nx_graph = nx.Graph()

        for edge in edges:
            edge = edge["r"]
            source = edge["Source"]
            target = edge["Target"]
            attr = {
                "Label": edge["Label"],
                "label_attribute": edge["label_attribute"],
                "Id": edge["Id"]
            }
            nx_graph.add_edge(source, target, **attr)

        for node in nodes:
            node = node["n"]
            node_id = node["Id"]
            nx_node = nx_graph.node[node_id]
            for attr in node.keys():
                nx_node[attr] = node[attr]

        return nx_graph 
Example #24
Source File: exportnx.py    From GraphiPy with MIT License 5 votes vote down vote up
def create_from_csv(self, filepath, nx_graph=None, directional=False):

        if nx_graph is None:
            if directional:
                nx_graph = nx.DiGraph()
            else:
                nx_graph = nx.Graph()

        nodes_path = filepath + "nodes\\"
        edges_path = filepath + "edges\\"

        for filename in os.listdir(edges_path):
            reader = csv.DictReader(
                open(edges_path + filename, encoding="utf-8"))
            for edge in reader:
                source = edge["Source"]
                target = edge["Target"]
                attr = {
                    "Label": edge["Label"],
                    "label_attribute": edge["label_attribute"],
                    "Id": edge["Id"]
                }
                nx_graph.add_edge(source, target, **attr)

        for filename in os.listdir(nodes_path):
            reader = csv.DictReader(
                open(nodes_path + filename, encoding="utf-8"))
            for node in reader:
                node_id = node["Id"]
                nx_node = nx_graph.node[node_id]
                for attr in node.keys():
                    nx_node[attr] = node[attr]

        return nx_graph 
Example #25
Source File: comment_tree.py    From news-popularity-prediction with Apache License 2.0 5 votes vote down vote up
def calculate_max_depth(comment_tree):
    comment_tree_nx = nx.from_scipy_sparse_matrix(comment_tree, create_using=nx.Graph())

    if len(comment_tree_nx) == 0:
        max_depth = 0.0
    else:
        node_to_depth = nx.shortest_path_length(comment_tree_nx, 0)
        max_depth = max(node_to_depth.values())

    return max_depth 
Example #26
Source File: exportnx.py    From GraphiPy with MIT License 5 votes vote down vote up
def create_from_dict(self, dict_graph, nx_graph=None, directional=False):
        nodes_dict = dict_graph.get_nodes()
        edges_dict = dict_graph.get_edges()

        # Create graph from edge dictionaries
        if nx_graph is None:
            if directional:
                nx_graph = nx.DiGraph()
            else:
                nx_graph = nx.Graph()

        for key in edges_dict:
            edges = edges_dict[key]

            for edge in edges.values():
                source = edge.Source
                target = edge.Target
                attr = {
                    "Label": edge.Label,
                    "label_attribute": edge.label_attribute,
                    "Id": edge.Id
                }
                nx_graph.add_edge(source, target, **attr)

        # Add node attributes
        for key in nodes_dict:
            nodes = nodes_dict[key]

            for key in nodes.keys():
                node = vars(nodes[key])
                nx_node = nx_graph.node[key]

                for attr in node.keys():
                    nx_node[attr] = node[attr]

        return nx_graph 
Example #27
Source File: test_dusc_path.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_one_branch():
    global G
    G = nx.Graph()
    G.add_edge('A', 'B', cost=1)
    G.add_edge('B', 'C', cost=1)
    G.add_edge('B', 'D', cost=1)
    G.add_edge('C', 'E', cost=1)
    visited = init('A')

    print('Visited : ',  visited)

    # both order are valid
    assert visited == ['A', 'B', 'D', 'C', 'E'] or \
        visited == ['A', 'B', 'C', 'D', 'E']
    print('\n\n') 
Example #28
Source File: test_convert.py    From pytorch_geometric with MIT License 5 votes vote down vote up
def test_from_networkx_non_numeric_labels():
    graph = nx.Graph()
    graph.add_node('4')
    graph.add_node('2')
    graph.add_edge('4', '2')
    for node in graph.nodes():
        graph.nodes[node]['x'] = node
    data = from_networkx(graph)
    assert len(data) == 2
    assert data.x == ['4', '2']
    assert data.edge_index.tolist() == [[0, 1], [1, 0]] 
Example #29
Source File: test_dusc_path.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_linear():
    # Simple linear uniform cost graph
    global G
    G = nx.Graph()
    G.add_edge('A', 'B', cost=1)  # default edge data=1
    G.add_edge('B', 'C', cost=1)  # specify edge data
    G.add_edge('C', 'D', cost=1)
    visited = init('A')
    print('Visited : ',  visited)

    assert visited == ['A', 'B', 'C', 'D']
    print('\n\n') 
Example #30
Source File: test_convert.py    From pytorch_geometric with MIT License 5 votes vote down vote up
def test_from_networkx_inverse():
    graph = nx.Graph()
    graph.add_node(3)
    graph.add_node(2)
    graph.add_node(1)
    graph.add_node(0)
    graph.add_edge(3, 1)
    graph.add_edge(2, 1)
    graph.add_edge(1, 0)

    data = from_networkx(graph)
    assert len(data) == 1
    assert data.edge_index.tolist() == [[0, 1, 2, 2, 2, 3], [2, 2, 0, 1, 3, 2]]