Python networkx.complete_graph() Examples
The following are 30
code examples of networkx.complete_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: test_plotter.py From pygraphistry with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_networkx2igraph(self): import networkx as nx ng = nx.complete_graph(3) [x, y] = [int(x) for x in nx.__version__.split('.')] if x == 1: nx.set_node_attributes(ng, 'vattrib', 0) nx.set_edge_attributes(ng, 'eattrib', 1) else: nx.set_node_attributes(ng, 0, 'vattrib') nx.set_edge_attributes(ng, 1, 'eattrib') (e, n) = graphistry.bind(source='src', destination='dst').networkx2pandas(ng) edges = pd.DataFrame({ 'dst': {0: 1, 1: 2, 2: 2}, 'src': {0: 0, 1: 0, 2: 1}, 'eattrib': {0: 1, 1: 1, 2: 1} }) nodes = pd.DataFrame({ '__nodeid__': {0: 0, 1: 1, 2: 2}, 'vattrib': {0: 0, 1: 0, 2: 0} }) assertFrameEqual(e, edges) assertFrameEqual(n, nodes)
Example #2
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 6 votes |
def test_correct_vector_returned(self, monkeypatch): """Test if function correctly constructs the feature vector. The ``prob_orbit_exact`` and ``prob_orbit_mc`` function called within ``feature_vector_orbits`` are monkeypatched to return hard-coded outputs that depend only on the orbit.""" with monkeypatch.context() as m: m.setattr( similarity, "prob_orbit_mc", lambda _graph, orbit, n_mean, samples, loss: 1.0 / sum(orbit), ) graph = nx.complete_graph(8) assert similarity.feature_vector_orbits(graph, [[1, 1], [2, 1, 1]], samples=1) == [ 0.5, 0.25, ] with monkeypatch.context() as m: m.setattr( similarity, "prob_orbit_exact", lambda _graph, orbit, n_mean, loss: 0.5 * (1.0 / sum(orbit)), ) graph = nx.complete_graph(8) assert similarity.feature_vector_orbits(graph, [[1, 1], [2, 1, 1]]) == [0.25, 0.125]
Example #3
Source File: test_clique.py From strawberryfields with Apache License 2.0 | 6 votes |
def test_grow_maximal_weight(self, dim): """Test if function grows to expected maximal graph when weight-based node selection is used. The chosen graph is a fully connected graph where the final three nodes have subsequently been disconnected from each other, but remain connected to all the other nodes. We then start from the clique composed of all but the final three nodes and seek to grow. In this construction, we can add just one of the final three nodes. This test gives the final node the largest weight, so we expect that one to be added.""" graph = nx.complete_graph(dim) s = graph.subgraph([dim - 3, dim - 2, dim - 1]) for e in s.edges(): graph.remove_edge(*e) s = set(range(dim - 3)) weights = list(range(dim)) target = s | {dim - 1} assert set(clique.grow(s, graph, node_select=weights)) == target
Example #4
Source File: test_decomposers.py From dwave-hybrid with Apache License 2.0 | 6 votes |
def test_nx_pfs_deep_search(self): pfs = EnergyImpactDecomposer._pfs_nodes # two K4 graphs connected with one edge graph = nx.complete_graph(4) graph.add_edges_from(nx.complete_graph(range(4,8)).edges) graph.add_edge(1, 4) # use node index for weight/priority priority = lambda node: node # make sure once the second cluster is within reach, we deplete it self.assertEqual(set(pfs(graph, 3, 2, priority)), set([2, 3])) self.assertEqual(set(pfs(graph, 3, 3, priority)), set([1, 2, 3])) self.assertEqual(set(pfs(graph, 3, 4, priority)), set([1, 2, 3, 4])) self.assertEqual(set(pfs(graph, 3, 7, priority)), set([1, 2, 3, 4, 5, 6, 7])) self.assertEqual(set(pfs(graph, 3, 8, priority)), set([0, 1, 2, 3, 4, 5, 6, 7]))
Example #5
Source File: clique.py From strawberryfields with Apache License 2.0 | 6 votes |
def is_clique(graph: nx.Graph) -> bool: """Determines if the input graph is a clique. A clique of :math:`n` nodes has exactly :math:`n( n-1)/2` edges. **Example usage:** >>> graph = nx.complete_graph(10) >>> is_clique(graph) True Args: graph (nx.Graph): the input graph Returns: bool: ``True`` if input graph is a clique and ``False`` otherwise """ edges = graph.edges nodes = graph.order() return len(edges) == nodes * (nodes - 1) / 2
Example #6
Source File: test_clique.py From strawberryfields with Apache License 2.0 | 6 votes |
def test_grow_maximal_degree_tie(self, dim, monkeypatch): """Test if function grows using randomness to break ties during degree-based node selection. The chosen graph is a fully connected graph with the ``dim - 2`` and ``dim - 1`` nodes then disconnected. Starting from the first ``dim - 3`` nodes, one can add either of the ``dim - 2`` and ``dim - 1`` nodes. As they have the same degree, they should be selected randomly with equal probability. This function monkeypatches the ``np.random.choice`` call to guarantee that one of the nodes is picked during one run of ``grow`` and the other node is picked during the next run.""" graph = nx.complete_graph(dim) graph.remove_edge(dim - 2, dim - 1) s = set(range(dim - 2)) patch_random_choice_1 = functools.partial(patch_random_choice, element=0) patch_random_choice_2 = functools.partial(patch_random_choice, element=1) with monkeypatch.context() as m: m.setattr(np.random, "choice", patch_random_choice_1) c1 = clique.grow(s, graph, node_select="degree") with monkeypatch.context() as m: m.setattr(np.random, "choice", patch_random_choice_2) c2 = clique.grow(s, graph, node_select="degree") assert c1 != c2
Example #7
Source File: test_clique.py From strawberryfields with Apache License 2.0 | 6 votes |
def test_dead_end(self, monkeypatch): """Test if function stops when in a dead end (i.e., ``grow == swap``) such that no swapping is possible. This is achieved by monkeypatching ``grow`` and ``swap`` so that they simply return the same clique as fed in, which should cause the local search algorithm to conclude that it is already in a dead end and return the same clique.""" graph = nx.complete_graph(5) c = [0, 1, 2] with monkeypatch.context() as m: m.setattr(clique, "grow", patch_resize) m.setattr(clique, "swap", patch_resize) result = clique.search(c, graph, iterations=100) assert result == c
Example #8
Source File: test_subgraph.py From strawberryfields with Apache License 2.0 | 6 votes |
def test_weight_and_degree_ties(self, dim, monkeypatch, elem): """Test if function correctly resizes on a fixed example where the ideal resizing is known and node-weight based selection is used to settle ties, but with all node weights equal so that they must be settled uniformly at random. The example is a complete graph with a starting subgraph of the first ``dim - 2`` nodes. The task is to resize to one node smaller and larger. This test monkeypatches the ``np.random.choice`` call used in the function so that instead it returns a fixed element. This element is set to 0 or 1 in the test, resulting in different nodes being added and removed from the starting subgraph.""" g = nx.complete_graph(dim) s = list(range(dim - 2)) min_size = dim - 3 max_size = dim - 1 w = [1] * dim choice_elem = functools.partial(self.choice, element=elem) ideal = {dim - 2: s, dim - 1: s + [dim - 2 + elem], dim - 3: list(set(s) - {elem})} with monkeypatch.context() as m: m.setattr(np.random, "choice", choice_elem) resized = subgraph.resize(s, g, min_size, max_size, node_select=w) assert resized == ideal
Example #9
Source File: test_subgraph.py From strawberryfields with Apache License 2.0 | 6 votes |
def test_tie(self, monkeypatch): """Test if function correctly settles ties with random selection. This test starts with the problem of a 6-dimensional complete graph and a 4-node subgraph, with the objective of shrinking down to 3 nodes. In this case, any of the 4 nodes in the subgraph is an equally good candidate for removal since all nodes have the same degree. The test monkeypatches the ``np.random.choice`` function to simply choose a fixed element, e.g. the element 2 of the list [0, 1, 2, 3] will be 2. Using this we expect the node to be removed by ``resize`` in this case to have label equal to the element.""" dim = 6 g = nx.complete_graph(dim) s = [0, 1, 2, 3] for i in range(4): choice_i = functools.partial(self.choice, element=i) with monkeypatch.context() as m: m.setattr(np.random, "choice", choice_i) resized = subgraph.resize(s, g, min_size=3, max_size=3) resized_subgraph = resized[3] removed_node = list(set(s) - set(resized_subgraph))[0] assert removed_node == i
Example #10
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_invalid_loss(self): """Test if function raises a ``ValueError`` when the loss parameter is specified outside of range.""" g = nx.complete_graph(5) with pytest.raises( ValueError, match="Loss parameter must take a value between zero and one" ): similarity.prob_event_mc(g, 2, 2, loss=2)
Example #11
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_max_loss(self): """Test if function samples from the vacuum when maximum loss is applied.""" graph = nx.complete_graph(5) assert similarity.prob_orbit_mc(graph, [1, 1, 1, 1], samples=1, loss=1) == 0.0
Example #12
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_invalid_photon_number(self): """Test if function raises a ``ValueError`` when a photon number below zero is specified""" g = nx.complete_graph(5) with pytest.raises(ValueError, match="Photon number must not be below zero"): similarity.prob_event_mc(g, -1, 2)
Example #13
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_low_count(self): """Test if function raises a ``ValueError`` if ``max_count_per_mode`` is negative.""" g = nx.complete_graph(5) with pytest.raises( ValueError, match="Maximum number of photons per mode must be non-negative" ): similarity.prob_event_mc(g, 2, max_count_per_mode=-1)
Example #14
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_prob_vacuum_event(self): """Tests if the function gives the right probability for an event with zero photons when the GBS device has been configured to have zero mean photon number.""" graph = nx.complete_graph(5) assert similarity.prob_event_mc(graph, 0, 0, 0) == 1.0
Example #15
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_bad_event_photon_numbers(self): """Test if function raises a ``ValueError`` when input a minimum photon number that is below zero.""" with pytest.raises(ValueError, match="Cannot request events with photon number below zero"): graph = nx.complete_graph(5) similarity.feature_vector_events(graph, [-1, 4], 2)
Example #16
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_calls_exact_for_zero_samples(self): """Test if function calls the exact function for zero samples""" g = nx.complete_graph(5) assert similarity.feature_vector_events( g, [2], 1, samples=0 ) == similarity.prob_event_exact(g, 2, 1)
Example #17
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_low_count(self): """Test if function raises a ``ValueError`` if ``max_count_per_mode`` is negative.""" g = nx.complete_graph(5) with pytest.raises( ValueError, match="Maximum number of photons per mode must be non-negative" ): similarity.feature_vector_events(g, [2, 4], max_count_per_mode=-1)
Example #18
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_invalid_n_mean(self): """Test if function raises a ``ValueError`` when the mean photon number is specified to be negative.""" g = nx.complete_graph(5) with pytest.raises(ValueError, match="Mean photon number must be non-negative"): similarity.prob_event_mc(g, 2, 2, n_mean=-1)
Example #19
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_known_result(self): """Tests if the probability for known cases is correctly reproduced.""" g = nx.complete_graph(3) assert np.allclose(similarity.prob_orbit_mc(g, [1, 1], 2), 0.2422152682538481) assert np.allclose(similarity.prob_orbit_mc(g, [4], 1), 0)
Example #20
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_invalid_photon_number(self): """Test if function raises a ``ValueError`` when a photon number below zero is specified""" g = nx.complete_graph(5) with pytest.raises(ValueError, match="Photon number must not be below zero"): similarity.prob_event_exact(g, -1, 2)
Example #21
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_prob_vacuum_orbit(self): """Tests if the function gives the right probability for the empty orbit when the GBS device has been configured to have zero mean photon number.""" graph = nx.complete_graph(5) assert similarity.prob_orbit_mc(graph, [], 0) == 1.0
Example #22
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_odd_photon_numbers(self, k): """Test if function returns zero probability for odd number of total photons.""" graph = nx.complete_graph(10) assert similarity.prob_orbit_mc(graph, [k]) == 0.0
Example #23
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_mean_computation_orbit(self, monkeypatch): """Tests if the calculation of the sample mean is performed correctly. The test monkeypatches the fock_prob function so that the probability is the same for each sample and is equal to 1/5, i.e., one over the cardinality of the orbit [1,1,1,1] for 5 modes.""" graph = nx.complete_graph(5) with monkeypatch.context() as m: m.setattr( "strawberryfields.backends.BaseGaussianState.fock_prob", lambda *args, **kwargs: 0.2, ) assert np.allclose(similarity.prob_orbit_mc(graph, [1, 1, 1, 1]), 1.0)
Example #24
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_invalid_n_mean(self): """Test if function raises a ``ValueError`` when the mean photon number is specified to be negative.""" g = nx.complete_graph(5) with pytest.raises(ValueError, match="Mean photon number must be non-negative"): similarity.prob_orbit_mc(g, [1, 1, 1, 1], n_mean=-1)
Example #25
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_invalid_samples(self): """Test if function raises a ``ValueError`` when a number of samples less than one is requested.""" g = nx.complete_graph(5) with pytest.raises(ValueError, match="Number of samples must be at least one"): similarity.prob_orbit_mc(g, [1, 1, 1, 1], samples=0)
Example #26
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_known_result(self): """Tests if the probability for known cases is correctly reproduced.""" graph = nx.complete_graph(4) p1 = similarity.prob_event_exact(graph, 2, 2, 1) p2 = similarity.prob_event_exact(graph, 2, 1, 1) p3 = similarity.prob_orbit_exact(graph, [1, 1], 1) p4 = similarity.prob_event_exact(graph, 2, 2, 4) assert np.allclose(p1 - p2, 0) assert np.allclose(p2, p3) assert np.allclose(p4, 0.21087781178526066)
Example #27
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_correct_result_returned(self, monkeypatch): """Tests if the call to _get_state function is performed correctly and probabilities over all constituent orbits of the given event are summed correctly. The test monkeypatches the fock_prob function so that the probability is the same for each sample permutation of all constituent orbits and is equal to 1/8. For a 4-mode graph, an event with ``photon_number = 2``, and ``max_count_per_mode = 1`` contains orbit [1, 1] which has 6 possible sample permutations.""" graph = nx.complete_graph(4) with monkeypatch.context() as m: m.setattr( "strawberryfields.backends.BaseGaussianState.fock_prob", lambda *args, **kwargs: 1 / 8, ) assert similarity.prob_event_exact(graph, 2, 1) == 6 / 8
Example #28
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_odd_photon_numbers(self, k, nmax): """Test if function returns zero probability for odd number of total photons.""" graph = nx.complete_graph(10) assert similarity.prob_event_exact(graph, k, nmax) == 0.0
Example #29
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_low_count(self): """Test if function raises a ``ValueError`` if ``max_count_per_mode`` is negative.""" g = nx.complete_graph(5) with pytest.raises( ValueError, match="Maximum number of photons per mode must be non-negative" ): similarity.prob_event_exact(g, 2, max_count_per_mode=-1)
Example #30
Source File: test_similarity.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_prob_vacuum_orbit(self): """Tests if the function gives the right probability for the empty orbit when the GBS device has been configured to have zero mean photon number.""" graph = nx.complete_graph(5) assert similarity.prob_orbit_exact(graph, [], 0) == 1.0