Python networkx.MultiDiGraph() Examples

The following are 30 code examples of networkx.MultiDiGraph(). 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: dagcircuit.py    From qiskit-terra with Apache License 2.0 7 votes vote down vote up
def from_networkx(cls, graph):
        """Take a networkx MultiDigraph and create a new DAGCircuit.

        Args:
            graph (networkx.MultiDiGraph): The graph to create a DAGCircuit
                object from. The format of this MultiDiGraph format must be
                in the same format as returned by to_networkx.

        Returns:
            DAGCircuit: The dagcircuit object created from the networkx
                MultiDiGraph.
        """

        dag = DAGCircuit()
        for node in nx.topological_sort(graph):
            if node.type == 'out':
                continue
            if node.type == 'in':
                dag._add_wire(node.wire)
            elif node.type == 'op':
                dag.apply_operation_back(node.op.copy(), node.qargs,
                                         node.cargs, node.condition)
        return dag 
Example #2
Source File: dependencygraph.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def nx_graph(self):
        """Convert the data in a ``nodelist`` into a networkx labeled directed graph."""
        import networkx

        nx_nodelist = list(range(1, len(self.nodes)))
        nx_edgelist = [
            (n, self._hd(n), self._rel(n))
            for n in nx_nodelist if self._hd(n)
        ]
        self.nx_labels = {}
        for n in nx_nodelist:
            self.nx_labels[n] = self.nodes[n]['word']

        g = networkx.MultiDiGraph()
        g.add_nodes_from(nx_nodelist)
        g.add_edges_from(nx_edgelist)

        return g 
Example #3
Source File: model_component_test.py    From MXFusion with Apache License 2.0 6 votes vote down vote up
def test_switch_simple_backwards(self):

        node_a = mfc.ModelComponent()
        node_b = mfc.ModelComponent()
        node_c = mfc.ModelComponent()
        node_a.predecessors = [('edge_1', node_b), ('edge_2', node_c)]
        node_b.successors = [('edge_1', node_a)]
        node_c.successors = [('edge_2', node_a)]
        #
        # successors = set([(node_b.uuid, node_a.uuid), (node_c.uuid, node_a.uuid)])

        graph = nx.MultiDiGraph()

        node_a.graph = graph

        self.assertTrue(set([v for _, v in node_b.successors]) == set([node_a]))
        self.assertTrue(set([v for _, v in node_c.successors]) == set([node_a]))
        self.assertTrue(set([v for _, v in node_a.predecessors]) == set([node_c, node_b])) 
Example #4
Source File: model_component_test.py    From MXFusion with Apache License 2.0 6 votes vote down vote up
def test_switch_multilayer(self):

        node_a = mfc.ModelComponent()
        node_b = mfc.ModelComponent()
        node_c = mfc.ModelComponent()
        node_d = mfc.ModelComponent()
        node_e = mfc.ModelComponent()
        node_a.predecessors = [('edge_1', node_b), ('edge_2', node_c)]
        node_b.predecessors = [('edge_1', node_d), ('edge_2', node_e)]

        graph = nx.MultiDiGraph()

        node_a.graph = graph

        self.assertTrue(set([v for _, v in node_b.successors]) == set([node_a]))
        self.assertTrue(set([v for _, v in node_c.successors]) == set([node_a]))
        self.assertTrue(set([v for _, v in node_a.predecessors]) == set([node_c, node_b]))

        self.assertTrue(set([v for _, v in node_d.successors]) == set([node_b]))
        self.assertTrue(set([v for _, v in node_e.successors]) == set([node_b]))
        self.assertTrue(set([v for _, v in node_b.predecessors]) == set([node_d, node_e])) 
Example #5
Source File: graph_index.py    From dgl with Apache License 2.0 6 votes vote down vote up
def to_networkx(self):
        """Convert to networkx graph.

        The edge id will be saved as the 'id' edge attribute.

        Returns
        -------
        networkx.DiGraph
            The nx graph
        """
        src, dst, eid = self.edges()
        # xiangsx: Always treat graph as multigraph
        ret = nx.MultiDiGraph()
        ret.add_nodes_from(range(self.number_of_nodes()))
        for u, v, e in zip(src, dst, eid):
            ret.add_edge(u, v, id=e)
        return ret 
Example #6
Source File: model_component_test.py    From MXFusion with Apache License 2.0 6 votes vote down vote up
def test_join_attach_new_successor_not_to_graph(self):

        node_a = mfc.ModelComponent()
        graph = nx.MultiDiGraph()

        node_b = mfc.ModelComponent()
        node_d = mfc.ModelComponent()
        node_e = mfc.ModelComponent()
        node_b.predecessors = [('edge_1', node_d), ('edge_2', node_e)]
        node_b.graph = graph

        node_c = mfc.ModelComponent()
        node_a.predecessors = [('edge_1', node_b), ('edge_2', node_c)]

        self.assertTrue(set([v for _, v in node_b.successors]) == set([node_a]))
        self.assertTrue(set([v for _, v in node_c.successors]) == set([node_a]))
        self.assertTrue(set([v for _, v in node_a.predecessors]) == set([node_c, node_b]))

        self.assertTrue(set([v for _, v in node_d.successors]) == set([node_b]))
        self.assertTrue(set([v for _, v in node_e.successors]) == set([node_b]))
        self.assertTrue(set([v for _, v in node_b.predecessors]) == set([node_d, node_e])) 
Example #7
Source File: model_component_test.py    From MXFusion with Apache License 2.0 6 votes vote down vote up
def test_join_successors_not_in_graph_to_node_in_graph(self):
        node_a = mfc.ModelComponent()
        node_b = mfc.ModelComponent()
        node_d = mfc.ModelComponent()
        node_e = mfc.ModelComponent()
        node_b.successors = [('edge_1', node_d), ('edge_2', node_e)]
        graph = nx.MultiDiGraph()

        node_a.graph = graph
        node_a.successors = [('edge_1', node_b)]

        self.assertTrue(set([v for _, v in node_a.successors]) == set([node_b]))
        self.assertTrue(set([v for _, v in node_b.predecessors]) == set([node_a]))

        self.assertTrue(set([v for _, v in node_d.predecessors]) == set([node_b]))
        self.assertTrue(set([v for _, v in node_e.predecessors]) == set([node_b]))
        self.assertTrue(set([v for _, v in node_b.successors]) == set([node_d, node_e])) 
Example #8
Source File: scigraph_ontology.py    From ontobio with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def subgraph(self, nodes=None, relations=None):
        if nodes is None:
            nodes = []
        r_nodes = []
        r_edges = []
        
        logger.debug("Scigraph, Subgraph for {}".format(nodes))
        for n in nodes:
            logger.debug("Parents-of {}".format(n))
            g = self._neighbors_graph(id=n,
                                      direction='OUTGOING',
                                      depth=1,
                                      relationshipType=self._mkrel(relations))
            r_nodes += g['nodes']
            r_edges += g['edges']
        digraph = nx.MultiDiGraph()
        for n in r_nodes:
            digraph.add_node(n['id'], **self._repair(n))
        for e in r_edges:
            digraph.add_edge(e['obj'],e['sub'], pred=e['pred'])
        return digraph


    # Override 
Example #9
Source File: model_component_test.py    From MXFusion with Apache License 2.0 6 votes vote down vote up
def test_switch_simple_forwards(self):

        node_a = mfc.ModelComponent()
        node_b = mfc.ModelComponent()
        node_c = mfc.ModelComponent()
        node_a.predecessors = [('edge_1', node_b), ('edge_2', node_c)]
        node_b.successors = [('edge_1', node_a)]
        node_c.successors = [('edge_2', node_a)]

        graph = nx.MultiDiGraph()

        node_c.graph = graph

        self.assertTrue(set([v for _, v in node_b.successors]) == set([node_a]))
        self.assertTrue(set([v for _, v in node_c.successors]) == set([node_a]))
        self.assertTrue(set([v for _, v in node_a.predecessors]) == set([node_c, node_b])) 
Example #10
Source File: graphml.py    From pybel with MIT License 6 votes vote down vote up
def _to_graphml_simple(graph: BELGraph) -> nx.MultiDiGraph:
    """Convert a BEL graph to a simple graph.

    :param graph: A BEL graph
    """
    rv = nx.MultiDiGraph()

    for node in graph:
        rv.add_node(node.as_bel(), function=node.function)

    for u, v, key, edge_data in graph.edges(data=True, keys=True):
        u_key, v_key = u.as_bel(), v.as_bel()
        rv.add_edge(
            u_key,
            v_key,
            key=key,
            interaction=edge_data[RELATION],
            bel=graph.edge_to_bel(u, v, edge_data),
        )

    return rv 
Example #11
Source File: graphml.py    From pybel with MIT License 6 votes vote down vote up
def _to_graphml_umbrella(graph: BELGraph) -> nx.MultiDiGraph:
    """Convert a BEL graph to a new graph the nodes as original BEL terms strings.

    :param graph: A BEL graph
    """
    rv = nx.MultiDiGraph()

    for u, v, key, edge_data in graph.edges(data=True, keys=True):
        u_key, _, v_key = edge_to_tuple(u, v, edge_data)

        rv.add_edge(
            u_key,
            v_key,
            key=key,
            relation=edge_data[RELATION],
            bel=graph.edge_to_bel(u, v, edge_data),
        )

    return rv 
Example #12
Source File: test_random.py    From pybel with MIT License 6 votes vote down vote up
def test_random_nodes_inverted(self):
        """Test getting random nodes."""
        graph = nx.MultiDiGraph()

        graph.add_edge(1, 2)
        graph.add_edge(1, 3)
        graph.add_edge(1, 4)
        graph.add_edge(1, 5)

        n = 30000
        r = Counter(
            get_random_node(graph, set(), invert_degrees=True)
            for _ in range(n)
        )

        degree_sum = (1 / 4) + (1 / 1) + (1 / 1) + (1 / 1) + (1 / 1)

        self.assertAlmostEqual((1 / 4) / degree_sum, r[1] / n, places=2)
        self.assertAlmostEqual((1 / 1) / degree_sum, r[2] / n, places=2)
        self.assertAlmostEqual((1 / 1) / degree_sum, r[3] / n, places=2)
        self.assertAlmostEqual((1 / 1) / degree_sum, r[4] / n, places=2)
        self.assertAlmostEqual((1 / 1) / degree_sum, r[5] / n, places=2) 
Example #13
Source File: dagdependency.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
def _gather_succ(self, node_id, direct_succ):
        """
        Function set an attribute successors and gather multiple lists
        of direct successors into a single one.

        Args:
            node_id (int): label of the considered node in the DAG
            direct_succ (list): list of direct successors for the given node

        Returns:
            MultiDiGraph: with update of the attribute ['predecessors']
            the lists of direct successors are put into a single one
        """
        gather = self._multi_graph
        for d_succ in direct_succ:
            gather.get_node_data(node_id).successors.append([d_succ])
            succ = gather.get_node_data(d_succ).successors
            gather.get_node_data(node_id).successors.append(succ)
        return gather 
Example #14
Source File: drawing.py    From peregrine with MIT License 6 votes vote down vote up
def format_graph_for_json(graph, raise_errors=True):
    """
    Currently, only supported types for graph are Graph, DiGraph, MultiGraph, and MultiDiGraph. graph must
    be an instance of one of these types, not a class that inherits from one.
    """
    graph_dict = nx.to_dict_of_dicts(graph)
    graph_type = ''

    for key, value in accepted_types.items():
        if type(graph) == key:
            graph_type = value
            break

    if graph_type == '':
        if raise_errors:
            raise TypeError('parameter graph is not of the accepted types.graph is of'
                            'type {}'.format(str(type(graph))))
        else:
            graph_type = 'other'

    return {'graph_type': graph_type, 'graph_dict': graph_dict} 
Example #15
Source File: multi_exchange.py    From peregrine with MIT License 6 votes vote down vote up
def multi_graph_to_log_graph(digraph: nx.MultiDiGraph):
    """
    This does not work with the default version of Networkx, but with the fork available at wardbradt/Networkx

    Given weighted MultiDigraph m1, returns a MultiDigraph m2 where for each edge e1 in each edge bunch eb1 of m1, the
    weight w1 of e1 is replaced with log(w1) and the weight w2 of each edge e2 in the opposite edge bunch of eb is
    log(1/w2)

    This function is not optimized.

    todo: allow this function to be used with Networkx DiGraph objects. Should not be that hard, simply return seen
    from self._report in the iterator for digraph's edges() in reportviews.py as it is done for multidigraph's
    edge_bunches()
    """
    result_graph = nx.MultiDiGraph()
    for bunch in digraph.edge_bunches(data=True, seen=True):
        for data_dict in bunch[2]:
            weight = data_dict.pop('weight')
            # if not seen
            if not bunch[3]:
                result_graph.add_edge(bunch[0], bunch[1], -math.log(weight), **data_dict)
            else:
                result_graph.add_edge(bunch[0], bunch[1], -math.log(1/weight), **data_dict) 
Example #16
Source File: visualization.py    From rasa_core with Apache License 2.0 6 votes vote down vote up
def _add_default_nodes(graph: 'networkx.MultiDiGraph',
                       fontsize: int = 12) -> None:
    """Add the standard nodes we need."""

    graph.add_node(START_NODE_ID,
                   label="START",
                   fillcolor="green", style="filled", fontsize=fontsize,
                   **{"class": "start active"})
    graph.add_node(END_NODE_ID,
                   label="END",
                   fillcolor="red", style="filled", fontsize=fontsize,
                   **{"class": "end"})
    graph.add_node(TMP_NODE_ID,
                   label="TMP",
                   style="invis",
                   **{"class": "invisible"}) 
Example #17
Source File: visualization.py    From rasa_core with Apache License 2.0 6 votes vote down vote up
def _add_message_edge(graph: 'networkx.MultiDiGraph',
                      message: Dict[Text, Any],
                      current_node: int,
                      next_node_idx: int,
                      is_current: bool
                      ):
    """Create an edge based on the user message."""

    if message:
        message_key = sanitize(message.get("intent", {}).get("name", None))
        message_label = sanitize(message.get("text", None))
    else:
        message_key = None
        message_label = None

    _add_edge(graph, current_node, next_node_idx, message_key,
              message_label,
              **{"class": "active" if is_current else ""}) 
Example #18
Source File: test_pathfinding.py    From indra with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _setup_signed_graph():
    edges, signed_edges, edge_beliefs, all_ns = _digraph_setup()
    seg = nx.MultiDiGraph()

    seg.add_edges_from(signed_edges)
    # ATTN!! seg.edges yields u, v, index while seg.edges() yields u, v
    for u, v, sign in seg.edges:
        seg.edges[(u, v, sign)]['sign'] = sign
        seg.edges[(u, v, sign)]['belief'] = edge_beliefs[(u, v)]

    sng = signed_edges_to_signed_nodes(graph=seg, prune_nodes=True,
                                       copy_edge_data=True)
    for u, v in sng.edges:
        sng.edges[(u, v)]['weight'] = -np.log(sng.edges[(u, v)]['belief'])

    return seg, sng, all_ns 
Example #19
Source File: graphistry.py    From beagle with MIT License 6 votes vote down vote up
def anonymize_graph(self) -> "nx.MultiDiGraph":
        """Anonymizes the underlying graph before sending to Graphistry.

        Returns
        -------
        nx.MultiDiGraph
            The same graph structure, but without attributes.
        """

        json_graph = self.to_json()

        # Remove all properties from nodes, leave only IDs

        json_graph["nodes"] = [{"id": node["id"]} for node in json_graph["nodes"]]
        json_graph["links"] = [
            {"source": edge["source"], "target": edge["target"]} for edge in json_graph["links"]
        ]

        return nx.readwrite.json_graph.node_link_graph(json_graph) 
Example #20
Source File: dagcircuit.py    From quantumflow with Apache License 2.0 6 votes vote down vote up
def __init__(self, elements: Iterable[Operation]) -> None:
        G = nx.MultiDiGraph()

        for elem in elements:
            if isinstance(elem, tuple):  # Filter in and out nodes
                continue
            G.add_node(elem)
            for qubit in elem.qubits:
                qin = ('in', qubit)
                qout = ('out', qubit)
                if not G.has_node(qout):
                    G.add_edge(qin, qout)
                prev = list(G.predecessors(qout))[0]
                G.remove_edge(prev, qout)
                G.add_edge(prev, elem, key=qubit)
                G.add_edge(elem, qout, key=qubit)

        self.graph = G 
Example #21
Source File: test_random.py    From pybel with MIT License 6 votes vote down vote up
def test_random_nodes(self):
        """Test getting random nodes."""
        graph = nx.MultiDiGraph()

        graph.add_edge(1, 2)
        graph.add_edge(1, 3)
        graph.add_edge(1, 4)
        graph.add_edge(1, 5)

        n = 30000
        r = Counter(
            get_random_node(graph, set(), invert_degrees=False)
            for _ in range(n)
        )

        degree_sum = 4 + 1 + 1 + 1 + 1

        self.assertAlmostEqual(4 / degree_sum, r[1] / n, places=2)
        self.assertAlmostEqual(1 / degree_sum, r[2] / n, places=2)
        self.assertAlmostEqual(1 / degree_sum, r[3] / n, places=2)
        self.assertAlmostEqual(1 / degree_sum, r[4] / n, places=2)
        self.assertAlmostEqual(1 / degree_sum, r[5] / n, places=2) 
Example #22
Source File: visualization.py    From rasa_core with Apache License 2.0 5 votes vote down vote up
def _create_graph(fontsize: int = 12) -> 'networkx.MultiDiGraph':
    """Create a graph and adds the default nodes."""

    import networkx as nx
    graph = nx.MultiDiGraph()
    _add_default_nodes(graph, fontsize)
    return graph 
Example #23
Source File: dagcircuit.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def to_networkx(self):
        """Returns a copy of the DAGCircuit in networkx format."""
        # For backwards compatibility, return networkx structure from terra 0.12
        # where DAGNodes instances are used as indexes on the networkx graph.

        G = nx.MultiDiGraph()
        for node in self._get_multi_graph_nodes():
            G.add_node(node)
        for node in self.topological_nodes():
            for source_id, dest_id, edge in self._get_multi_graph_in_edges(node._node_id):
                G.add_edge(self._id_to_node[source_id], self._id_to_node[dest_id],
                           **edge)

        return G 
Example #24
Source File: apiutils.py    From aurum-datadiscovery with MIT License 5 votes vote down vote up
def __init__(self, data, operation):
        self._p_graph = nx.MultiDiGraph()
        op = operation.op
        params = operation.params
        self.populate_provenance(data, op, params)
        # cache for leafs and heads
        self._cached_leafs_and_heads = (None, None) 
Example #25
Source File: visualization.py    From rasa_core with Apache License 2.0 5 votes vote down vote up
def _remove_auxiliary_nodes(graph: 'networkx.MultiDiGraph',
                            special_node_idx: int) -> None:
    """Remove any temporary or unused nodes."""

    graph.remove_node(TMP_NODE_ID)

    if not len(list(graph.predecessors(END_NODE_ID))):
        graph.remove_node(END_NODE_ID)

    # remove duplicated "..." nodes after merging
    ps = set()
    for i in range(special_node_idx + 1, TMP_NODE_ID):
        for pred in list(graph.predecessors(i)):
            if pred in ps:
                graph.remove_node(i)
            else:
                ps.add(pred) 
Example #26
Source File: ontol.py    From ontobio with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_graph(self):
        """
        Return a networkx graph for the whole ontology.

        Note: Only implemented for *eager* implementations

        Return
        ------
        nx.MultiDiGraph
            A networkx MultiDiGraph object representing the complete ontology
        """
        return self.graph

    # consider caching 
Example #27
Source File: network.py    From lndmanage with MIT License 5 votes vote down vote up
def __init__(self, node):
        logger.info("Initializing network graph.")
        self.node = node
        self.edges = {}
        self.graph = nx.MultiDiGraph()
        self.cached_reading_graph_edges() 
Example #28
Source File: slimmer.py    From ontobio with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def remove_nodes(g, rmnodes):
    logger.info("Removing {} from {}".format(rmnodes,g))
    newg = nx.MultiDiGraph()
    for (n,nd) in g.nodes(data=True):
        if n not in rmnodes:
            newg.add_node(n, **nd)
            parents = _traverse(g, set([n]), set(rmnodes), set())
            for p in parents:
                newg.add_edge(p,n,**{'pred':'subClassOf'})
    return newg 
Example #29
Source File: sparql_ontol_utils.py    From ontobio with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_digraph(ont, relations=None, writecache=False):
    """
    Creates a basic graph object corresponding to a remote ontology
    """
    digraph = networkx.MultiDiGraph()
    logger.info("Getting edges (may be cached)")
    for (s,p,o) in get_edges(ont):
        p = map_legacy_pred(p)
        if relations is None or p in relations:
            digraph.add_edge(o,s,pred=p)
    logger.info("Getting labels (may be cached)")
    for (n,label) in fetchall_labels(ont):
        digraph.add_node(n, **{'label':label})
    return digraph 
Example #30
Source File: dagdependency.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def to_networkx(self):
        """Returns a copy of the DAGDependency in networkx format."""
        # For backwards compatibility, return networkx structure from terra 0.12
        # where DAGNodes instances are used as indexes on the networkx graph.

        dag_networkx = nx.MultiDiGraph()

        for node in self.get_nodes():
            dag_networkx.add_node(node)
        for node in self.topological_nodes():
            for source_id, dest_id, edge in \
                    self.get_in_edges(node.node_id):
                dag_networkx.add_edge(self.get_node(source_id), self.get_node(dest_id), **edge)
        return dag_networkx