Python networkx.is_isomorphic() Examples

The following are 30 code examples of networkx.is_isomorphic(). 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: test_indranet_assembler.py    From indra with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_to_digraph():
    ia = IndraNetAssembler([ab1, ab2, ab3, ab4, bc1, bc2, bc3, bc4])
    df = ia.make_df()
    net = IndraNet.from_df(df)
    assert len(net.nodes) == 3
    assert len(net.edges) == 8
    digraph = net.to_digraph(weight_mapping=_weight_mapping)
    assert len(digraph.nodes) == 3
    assert len(digraph.edges) == 2
    assert set([
        stmt['stmt_type'] for stmt in digraph['a']['b']['statements']]) == {
            'Activation', 'Phosphorylation', 'Inhibition', 'IncreaseAmount'}
    assert all(digraph.edges[e].get('belief', False) for e in digraph.edges)
    assert all(isinstance(digraph.edges[e]['belief'],
                          (float, np.longfloat)) for e in digraph.edges)
    assert all(digraph.edges[e].get('weight', False) for e in digraph.edges)
    assert all(isinstance(digraph.edges[e]['weight'],
                          (float, np.longfloat)) for e in digraph.edges)
    digraph_from_df = IndraNet.digraph_from_df(df)
    assert nx.is_isomorphic(digraph, digraph_from_df) 
Example #2
Source File: test_network.py    From IRCLogParser with GNU General Public License v3.0 6 votes vote down vote up
def test_identify_hubs_and_experts(self):
    
        top_hub_ = util.load_from_disk(self.test_data_dir + "hits/top_hub")
        top_keyword_overlap_ = util.load_from_disk(self.test_data_dir + "hits/top_keyword_overlap")
        top_auth_ = util.load_from_disk(self.test_data_dir + "hits/top_auth")
        message_graph = util.load_from_disk(self.test_data_dir + "hits/message_graph")
        
        capturedOutput = StringIO.StringIO()
        sys.stdout = capturedOutput
        
        message_num_graph, top_hub, top_keyword_overlap, top_auth = network.identify_hubs_and_experts(self.log_data, self.nicks, self.nick_same_list)
        
        sys.stdout = sys.__stdout__
        capturedOutput.close()
        
        self.assertEqual(top_hub, top_hub_)
        self.assertEqual(top_keyword_overlap, top_keyword_overlap_)
        self.assertEqual(top_auth, top_auth_) 
        self.assertTrue(nx.is_isomorphic(message_graph, message_num_graph)) 
Example #3
Source File: test_networkx.py    From beagle with MIT License 6 votes vote down vote up
def test_from_json_path(nx, tmpdir):
    proc = Process(process_id=10, process_image="test.exe", command_line=None)
    other_proc = Process(process_id=12, process_image="best.exe", command_line="best.exe /c 123456")

    proc.launched[other_proc]

    G = nx(nodes=[proc, other_proc])

    _json_output = NetworkX.graph_to_json(G)

    # Save to file
    p = tmpdir.mkdir("networkx").join("data.json")
    p.write(json.dumps(_json_output))

    G2 = NetworkX.from_json(p)

    # Graphs should be equal.
    assert networkx.is_isomorphic(G, G2) 
Example #4
Source File: test_networkx.py    From beagle with MIT License 6 votes vote down vote up
def test_from_json_object(nx):
    proc = Process(process_id=10, process_image="test.exe", command_line=None)
    other_proc = Process(process_id=12, process_image="best.exe", command_line="best.exe /c 123456")

    proc.launched[other_proc]

    G = nx(nodes=[proc, other_proc])

    _json_output = NetworkX.graph_to_json(G)

    assert isinstance(_json_output, dict)

    G2 = NetworkX.from_json(_json_output)

    # Graphs should be equal.
    assert networkx.is_isomorphic(G, G2) 
Example #5
Source File: historical_tests.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_subgraph_nbunch(self):
        nullgraph=nx.null_graph()
        K1=nx.complete_graph(1)
        K3=nx.complete_graph(3)
        K5=nx.complete_graph(5)
        # Test G.subgraph(nbunch), where nbunch is a single node
        H=K5.subgraph(1)
        assert_true(nx.is_isomorphic(H,K1))
        # Test G.subgraph(nbunch), where nbunch is a set
        H=K5.subgraph(set([1]))
        assert_true(nx.is_isomorphic(H,K1))
        # Test G.subgraph(nbunch), where nbunch is an iterator
        H=K5.subgraph(iter(K3))
        assert_true(nx.is_isomorphic(H,K3))
        # Test G.subgraph(nbunch), where nbunch is another graph
        H=K5.subgraph(K3)
        assert_true(nx.is_isomorphic(H,K3))
        H=K5.subgraph([9])
        assert_true(nx.is_isomorphic(H,nullgraph)) 
Example #6
Source File: test_network.py    From IRCLogParser with GNU General Public License v3.0 6 votes vote down vote up
def test_identify_hubs_and_experts(self):
        
        log_data = util.load_from_disk(self.test_data_dir + "hits/log_data")
        nicks = util.load_from_disk(self.test_data_dir + "hits/nicks")
        nick_same_list = util.load_from_disk(self.test_data_dir + "hits/nick_same_list")
        expected_top_hub = util.load_from_disk(self.test_data_dir + "hits/top_hub")
        expected_top_keyword_overlap = util.load_from_disk(self.test_data_dir + "hits/top_keyword_overlap")
        expected_top_auth = util.load_from_disk(self.test_data_dir + "hits/top_auth")
        message_graph = util.load_from_disk(self.test_data_dir + "hits/message_graph")
        
        capturedOutput = StringIO.StringIO()
        sys.stdout = capturedOutput
        
        message_num_graph, top_hub, top_keyword_overlap, top_auth = network.identify_hubs_and_experts(log_data, nicks, nick_same_list)
        
        sys.stdout = sys.__stdout__
        capturedOutput.close()

        self.assertEqual(top_hub, expected_top_hub)
        self.assertEqual(top_keyword_overlap, expected_top_keyword_overlap)
        self.assertEqual(top_auth, expected_top_auth)
        self.assertTrue(nx.is_isomorphic(message_graph, message_num_graph)) 
Example #7
Source File: test_userprofile.py    From IRCLogParser with GNU General Public License v3.0 6 votes vote down vote up
def test_identify_hubs_and_experts(self):

        expected_top_hub = util.load_from_disk(self.out_dir+ "top_hub")
        expected_top_keyword_overlap = util.load_from_disk(self.out_dir+ "top_keyword_overlap")
        expected_top_auth = util.load_from_disk(self.out_dir+ "top_auth")
        expected_message_graph = util.load_from_disk(self.out_dir + "message_num_graph")

        capturedOutput = StringIO.StringIO()
        sys.stdout = capturedOutput

        nicks, nick_same_list = nickTracker.nick_tracker(self.log_data)
        message_num_graph, top_hub, top_keyword_overlap, top_auth = network.identify_hubs_and_experts(self.log_data, nicks, nick_same_list)

        sys.stdout = sys.__stdout__
        capturedOutput.close()

        self.assertEqual(top_hub, expected_top_hub)
        self.assertEqual(top_keyword_overlap, expected_top_keyword_overlap)
        self.assertEqual(top_auth, expected_top_auth)
        self.assertTrue(nx.is_isomorphic(expected_message_graph, message_num_graph)) 
Example #8
Source File: test_network.py    From IRCLogParser with GNU General Public License v3.0 6 votes vote down vote up
def test_message_time_graph(self, mock_rec_list_splice, mock_correctLastCharCR, mock_get_year_month_day, mock_get_nick_sen_rec, mock_check_if_msg_line, mock_create_connected_nick_list, mock_to_graph):
        to_graph_ret = util.load_from_disk(self.test_data_dir + "message_time_graph/to_graph")
        
        conn_list = list(connected_components(to_graph_ret))
        
        mock_to_graph.return_value = to_graph_ret
        mock_rec_list_splice.side_effect = util.load_from_disk(self.test_data_dir + "message_time_graph/rec_list_splice")
        mock_create_connected_nick_list.return_value = util.load_from_disk(self.test_data_dir + "message_time_graph/conn_comp_list")
        mock_check_if_msg_line.side_effect = util.load_from_disk(self.test_data_dir + "message_time_graph/check_if_msg_line")
        mock_correctLastCharCR.side_effect = util.load_from_disk(self.test_data_dir + "message_time_graph/correctLastCharCR")
        mock_get_nick_sen_rec.side_effect = util.load_from_disk(self.test_data_dir + "message_time_graph/get_nick_sen_rec")
        #mock_correct_last_char_list.side_effect = util.load_from_disk(self.test_data_dir + "message_time_graph/correct_last_char_list")
        mock_get_year_month_day.side_effect = util.load_from_disk(self.test_data_dir + "message_time_graph/get_year_month_day")
        
        capturedOutput = StringIO.StringIO()
        sys.stdout = capturedOutput
        
        ret = network.message_time_graph(self.log_data, self.nicks, self.nick_same_list, DAY_BY_DAY_ANALYSIS=False)
        
        sys.stdout = sys.__stdout__
        capturedOutput.close()
        
        mock_to_graph.assert_called_once_with(self.nick_same_list)
        mock_create_connected_nick_list.assert_called_once_with(conn_list)
        self.assertTrue(nx.is_isomorphic(ret, util.load_from_disk(self.test_data_dir + "message_time_graph/msg_time_aggr_graph"))) 
Example #9
Source File: test_vf2userfunc.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_weightkey():
    g1 = nx.DiGraph()
    g2 = nx.DiGraph()

    g1.add_edge('A','B', weight=1)
    g2.add_edge('C','D', weight=0)

    assert_true(  nx.is_isomorphic(g1, g2) )
    em = iso.numerical_edge_match('nonexistent attribute', 1)
    assert_true(  nx.is_isomorphic(g1, g2, edge_match=em) )
    em = iso.numerical_edge_match('weight', 1)
    assert_false( nx.is_isomorphic(g1, g2, edge_match=em) )

    g2 = nx.DiGraph()
    g2.add_edge('C','D')
    assert_true( nx.is_isomorphic(g1, g2, edge_match=em) ) 
Example #10
Source File: topology_test.py    From SOL with MIT License 6 votes vote down vote up
def test_write_read(tmpdir):
    """
    Check that writing topology to disk and restoring it produces the
    expected result
    """
    dirname = u(os.path.abspath(tmpdir.dirname))
    topo = complete_topology(5)
    for l in topo.links():
        topo.set_resource(l, u'myresource', 4)
    topo.write_graph(dirname + os.path.sep + u'testgml.gml')
    topo2 = Topology(topo.name)
    topo2.load_graph(dirname + os.path.sep + u'testgml.gml')
    assert networkx.is_isomorphic(topo.get_graph(), topo2.get_graph())
    assert topo.name == topo2.name

    # Check that resources are preserved
    for n in topo.nodes():
        assert topo.get_resources(n) == topo2.get_resources(n)
    for l in topo.links():
        assert topo.get_resources(n) == topo2.get_resources(n) 
Example #11
Source File: infectious_disease.py    From ml-fairness-gym with Apache License 2.0 6 votes vote down vote up
def __eq__(self, other):
    if not isinstance(other, self.__class__):
      return False

    # We know these dicts have the same keys because 'other' is also a params
    # instance.
    self_dict = self.asdict()
    other_dict = other.asdict()

    for key in self_dict:
      if key == 'population_graph':
        if not nx.is_isomorphic(
            self_dict['population_graph'], other_dict['population_graph']):
          return False
      if (isinstance(self_dict[key], np.ndarray)
          and isinstance(other_dict[key], np.ndarray)):
        return (self_dict[key] == other_dict[key]).all()
      else:
        if self_dict[key] != other_dict[key]:
          return False
    return True 
Example #12
Source File: test_distance.py    From netrd with MIT License 6 votes vote down vote up
def test_weighted_input():
    G1 = nx.karate_club_graph()
    G2 = nx.karate_club_graph()
    rand = np.random.RandomState(seed=42)
    edge_weights = {e: rand.randint(0, 1000) for e in G2.edges}
    nx.set_edge_attributes(G2, edge_weights, "weight")
    assert nx.is_isomorphic(G1, G2)

    for label, obj in distance.__dict__.items():
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            if isinstance(obj, type) and BaseDistance in obj.__bases__:
                dist = obj().dist(G1, G2)
                warning_triggered = False
                for warning in w:
                    if "weighted" in str(warning.message):
                        warning_triggered = True
                if not warning_triggered:
                    assert not np.isclose(dist, 0.0)
                else:
                    assert np.isclose(dist, 0.0) 
Example #13
Source File: test_quantum_computer.py    From pyquil with Apache License 2.0 6 votes vote down vote up
def test_device_stuff():
    topo = nx.from_edgelist([(0, 4), (0, 99)])
    qc = QuantumComputer(
        name="testy!",
        qam=None,  # not necessary for this test
        device=NxDevice(topo),
        compiler=DummyCompiler(),
    )
    assert nx.is_isomorphic(qc.qubit_topology(), topo)

    isa = qc.get_isa(twoq_type="CPHASE")
    assert isa.edges[0].type == "CPHASE"
    assert isa.edges[0].targets == (0, 4)


# We sometimes narrowly miss the np.mean(parity) < 0.15 assertion, below. Alternatively, that upper
# bound could be relaxed. 
Example #14
Source File: test_chimera.py    From dwave_networkx with Apache License 2.0 6 votes vote down vote up
def test_nonsquare_coordinate_generator(self):
        #issue 149 found an issue with non-square generators -- let's be extra careful here
        for (m, n) in [(2, 4), (4, 2)]:
            G = dnx.chimera_graph(m, n, coordinates=True, data=True)
            H = dnx.chimera_graph(m, n, coordinates=False, data=True)
            self.assertTrue(nx.is_isomorphic(G, H))

            Gnodes = set(G.nodes)
            Glabels = set(q['linear_index'] for q in G.nodes.values())

            Hnodes = set(H.nodes)
            Hlabels = set(q['chimera_index'] for q in H.nodes.values())

            self.assertEqual(Gnodes, Hlabels)
            self.assertEqual(Hnodes, Glabels)

            coords = dnx.chimera_coordinates(m, n)
            F = nx.relabel_nodes(G, coords.chimera_to_linear, copy=True)
            self.assertEqual(set(map(frozenset, F.edges)), set(map(frozenset, H.edges)))

            E = nx.relabel_nodes(H, coords.linear_to_chimera, copy=True)
            self.assertEqual(set(map(frozenset, E.edges)), set(map(frozenset, G.edges))) 
Example #15
Source File: test_vf2userfunc.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_color1(self):
        assert_false(  nx.is_isomorphic(self.g1, self.g2, node_match=self.nm) ) 
Example #16
Source File: test_tree.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_graph(self):
        G=nx.DiGraph()
        G.add_nodes_from([1,2,3],color='red')
        G.add_edge(1,2,foo=7)
        G.add_edge(1,3,foo=10)
        G.add_edge(3,4,foo=10)
        H = tree_graph(tree_data(G,1))
        nx.is_isomorphic(G,H) 
Example #17
Source File: test_node_link.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_multigraph(self):
        G = nx.MultiGraph()
        G.add_edge(1,2,key='first')
        G.add_edge(1,2,key='second',color='blue')
        H = node_link_graph(node_link_data(G))
        nx.is_isomorphic(G,H)
        assert_equal(H[1][2]['second']['color'],'blue') 
Example #18
Source File: test_node_link.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_graph(self):
        G = nx.path_graph(4)
        H = node_link_graph(node_link_data(G))
        nx.is_isomorphic(G,H) 
Example #19
Source File: generators_test.py    From SOL with MIT License 5 votes vote down vote up
def test_chain_generators(size):
    """
    Some basic tests for chain topology generators. Ensure we return correct types
    and correct number of nodes.
    """
    topo = chain_topology(size)
    assert isinstance(topo, Topology)
    assert isinstance(topo.get_graph(), networkx.DiGraph)
    assert networkx.is_isomorphic(topo.get_graph().to_undirected(),
                                  networkx.path_graph(size)) 
Example #20
Source File: generators_test.py    From SOL with MIT License 5 votes vote down vote up
def test_complete_generators(size):
    """
    Some basic tests for complete topology generators. Ensure we return correct types
    and correct number of nodes.
    """
    topo = complete_topology(size)
    assert isinstance(topo, Topology)
    assert isinstance(topo.get_graph(), networkx.DiGraph)
    assert topo.num_nodes() == size
    assert networkx.is_isomorphic(topo.get_graph().to_undirected(),
                                  networkx.complete_graph(size)) 
Example #21
Source File: test_vf2userfunc.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_colors_only(self):
        gm = self.GM(self.g1, self.g2, edge_match=self.emc)
        assert_true( gm.is_isomorphic() ) 
Example #22
Source File: test_vf2userfunc.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_generic1(self):
        gm = self.GM(self.g1, self.g2, edge_match=self.emg1)
        assert_true( gm.is_isomorphic() ) 
Example #23
Source File: case.py    From kglib with Apache License 2.0 5 votes vote down vote up
def assertIsIsomorphic(self, graph_1, graph_2):
        try:
            self.assertTrue(nx.is_isomorphic(graph_1, graph_2,
                                             node_match=match_node_things,
                                             edge_match=match_edge_types))
        except AssertionError:
            raise AssertionError(
                "The two graphs are not isomorphic based on the data attached to the nodes and/or edges") 
Example #24
Source File: test_vf2userfunc.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_generic2(self):
        gm = self.GM(self.g1, self.g2, edge_match=self.emg2)
        assert_false( gm.is_isomorphic() ) 
Example #25
Source File: test_product.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_tensor_product_null():
    null = nx.null_graph()
    empty10 = nx.empty_graph(10)
    K3 = nx.complete_graph(3)
    K10 = nx.complete_graph(10)
    P3 = nx.path_graph(3)
    P10 = nx.path_graph(10)
    # null graph
    G = tensor_product(null, null)
    assert_true(nx.is_isomorphic(G, null))
    # null_graph X anything = null_graph and v.v.
    G = tensor_product(null, empty10)
    assert_true(nx.is_isomorphic(G, null))
    G = tensor_product(null, K3)
    assert_true(nx.is_isomorphic(G, null))
    G = tensor_product(null, K10)
    assert_true(nx.is_isomorphic(G, null))
    G = tensor_product(null, P3)
    assert_true(nx.is_isomorphic(G, null))
    G = tensor_product(null, P10)
    assert_true(nx.is_isomorphic(G, null))
    G = tensor_product(empty10, null)
    assert_true(nx.is_isomorphic(G, null))
    G = tensor_product(K3, null)
    assert_true(nx.is_isomorphic(G, null))
    G = tensor_product(K10, null)
    assert_true(nx.is_isomorphic(G, null))
    G = tensor_product(P3, null)
    assert_true(nx.is_isomorphic(G, null))
    G = tensor_product(P10, null)
    assert_true(nx.is_isomorphic(G, null)) 
Example #26
Source File: circuit_dag.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def __eq__(self, other):
        if not isinstance(other, type(self)):
            return NotImplemented
        g1 = self.copy()
        g2 = other.copy()
        for node, attr in g1.nodes(data=True):
            attr['val'] = node.val
        for node, attr in g2.nodes(data=True):
            attr['val'] = node.val
        def node_match(attr1: Dict[Any, Any], attr2: Dict[Any, Any]) -> bool:
            return attr1['val'] == attr2['val']
        return networkx.is_isomorphic(g1, g2, node_match=node_match) 
Example #27
Source File: circuit_specs.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def compile(self, seq, registers):
        """Class-specific circuit compilation method.

        If additional compilation logic is required, child classes can redefine this method.

        Args:
            seq (Sequence[Command]): quantum circuit to modify
            registers (Sequence[RegRefs]): quantum registers
        Returns:
            List[Command]: modified circuit
        Raises:
            CircuitError: the given circuit cannot be validated to belong to this circuit class
        """
        # registers is not used here, but may be used if the method is overwritten pylint: disable=unused-argument
        if self.graph is not None:
            # check topology
            DAG = pu.list_to_DAG(seq)

            # relabel the DAG nodes to integers, with attributes
            # specifying the operation name. This allows them to be
            # compared, rather than using Command objects.
            mapping = {i: n.op.__class__.__name__ for i, n in enumerate(DAG.nodes())}
            circuit = nx.convert_node_labels_to_integers(DAG)
            nx.set_node_attributes(circuit, mapping, name="name")

            def node_match(n1, n2):
                """Returns True if both nodes have the same name"""
                return n1["name"] == n2["name"]

            # check if topology matches
            if not nx.is_isomorphic(circuit, self.graph, node_match):
                # TODO: try and compile the program to match the topology
                # TODO: add support for parameter range matching/compilation
                raise pu.CircuitError(
                    "Program cannot be used with the CircuitSpec '{}' "
                    "due to incompatible topology.".format(self.short_name)
                )

        return seq 
Example #28
Source File: test_device.py    From pyquil with Apache License 2.0 5 votes vote down vote up
def test_NxDevice(isa_dict, noise_model_dict):
    graph = isa_to_graph(ISA.from_dict(isa_dict))
    nxdev = NxDevice(graph)

    device_raw = {
        "isa": isa_dict,
        "noise_model": noise_model_dict,
        "is_online": True,
        "is_retuning": False,
    }
    dev = Device(DEVICE_FIXTURE_NAME, device_raw)

    nx.is_isomorphic(nxdev.qubit_topology(), dev.qubit_topology())
    isa = nxdev.get_isa()
    assert isa.qubits[0].type == "Xhalves" 
Example #29
Source File: test_device.py    From pyquil with Apache License 2.0 5 votes vote down vote up
def test_isa_to_graph(isa_dict):
    graph = isa_to_graph(ISA.from_dict(isa_dict))
    should_be = nx.from_edgelist([(0, 1), (1, 2), (0, 2)])
    assert nx.is_isomorphic(graph, should_be) 
Example #30
Source File: test_adjacency.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_digraph(self):
        G = nx.DiGraph()
        G.add_path([1,2,3])
        H = adjacency_graph(adjacency_data(G))
        assert_true(H.is_directed())
        nx.is_isomorphic(G,H)