本文整理汇总了Python中networkx.density方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.density方法的具体用法?Python networkx.density怎么用?Python networkx.density使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.density方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _update_dict
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def _update_dict(d: dict, d_new: dict, max_count: int) -> None:
"""Updates dictionary ``d`` with subgraph tuples contained in ``d_new``.
Subgraph tuples are a pair of values: a float specifying the subgraph density and a list of
integers specifying the subgraph nodes. Both ``d`` and ``d_new`` are dictionaries over
different subgraph sizes. The values of ``d`` are lists of subgraph tuples containing the top
densest subgraphs for a given size, with maximum length ``max_count``. The values of
``d_new`` are candidate subgraph tuples that can be the result of resizing an input subgraph
over a range using :func:`resize`. We want to add these candidates to the list of subgraph
tuples in ``d`` to build up our collection of dense subgraphs.
Args:
d (dict[int, list[tuple[float, list[int]]]]): dictionary of subgraph sizes and
corresponding list of subgraph tuples
d_new (dict[int, tuple[float, list[int]]]): dictionary of subgraph sizes and corresponding
subgraph tuples that are candidates to be added to the list
max_count (int): the maximum length of every subgraph tuple list
Returns:
None: this function modifies the dictionary ``d`` in place
"""
for size, t in d_new.items():
l = d.setdefault(size, [t])
_update_subgraphs_list(l, t, max_count)
示例2: list
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def list(self) -> List[Tuple[str, float]]:
"""Return a list of tuples that summarize the graph."""
number_nodes = self.graph.number_of_nodes()
return [
('Name', self.graph.name),
('Version', self.graph.version),
('Number of Nodes', number_nodes),
('Number of Namespaces', len(self.graph.count.namespaces())),
('Number of Edges', self.graph.number_of_edges()),
('Number of Annotations', len(self.graph.count.annotations())),
('Number of Citations', self.graph.number_of_citations()),
('Number of Authors', self.graph.number_of_authors()),
('Network Density', '{:.2E}'.format(nx.density(self.graph))),
('Number of Components', nx.number_weakly_connected_components(self.graph)),
('Number of Warnings', self.graph.number_of_warnings()),
]
示例3: _common_format
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def _common_format(g, edge_notation):
lines = []
lines.append("Name: %s" % g.name)
lines.append("Type: %s" % type(g).__name__)
lines.append("Frozen: %s" % nx.is_frozen(g))
lines.append("Density: %0.3f" % nx.density(g))
lines.append("Nodes: %s" % g.number_of_nodes())
for n, n_data in g.nodes(data=True):
if n_data:
lines.append(" - %s (%s)" % (n, n_data))
else:
lines.append(" - %s" % n)
lines.append("Edges: %s" % g.number_of_edges())
for (u, v, e_data) in g.edges(data=True):
if e_data:
lines.append(" %s %s %s (%s)" % (u, edge_notation, v, e_data))
else:
lines.append(" %s %s %s" % (u, edge_notation, v))
return lines
示例4: pformat
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def pformat(self):
"""Pretty formats your graph into a string.
This pretty formatted string representation includes many useful
details about your graph, including; name, type, frozeness, node count,
nodes, edge count, edges, graph density and graph cycles (if any).
"""
lines = _common_format(self, "->")
cycles = list(nx.cycles.recursive_simple_cycles(self))
lines.append("Cycles: %s" % len(cycles))
for cycle in cycles:
buf = six.StringIO()
buf.write("%s" % (cycle[0]))
for i in range(1, len(cycle)):
buf.write(" --> %s" % (cycle[i]))
buf.write(" --> %s" % (cycle[0]))
lines.append(" %s" % buf.getvalue())
return os.linesep.join(lines)
示例5: scaled_density
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def scaled_density(graph, communities, **kwargs):
"""Scaled density.
The scaled density of a community is defined as the ratio of the community density w.r.t. the complete graph density.
:param graph: a networkx/igraph object
:param communities: NodeClustering object
:param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
:return: If **summary==True** a FitnessResult object, otherwise a list of floats.
Example:
>>> from cdlib.algorithms import louvain
>>> from cdlib import evaluation
>>> g = nx.karate_club_graph()
>>> communities = louvain(g)
>>> scd = evaluation.scaled_density(g,communities)
"""
return __quality_indexes(graph, communities,
lambda graph, coms: nx.density(nx.subgraph(graph, coms)) / nx.density(graph), **kwargs)
示例6: test_clique_removal
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def test_clique_removal():
graph = nx.complete_graph(10)
i, cs = apxa.clique_removal(graph)
idens = nx.density(graph.subgraph(i))
eq_(idens, 0.0, "i-set not found by clique_removal!")
for clique in cs:
cdens = nx.density(graph.subgraph(clique))
eq_(cdens, 1.0, "clique not found by clique_removal!")
graph = nx.trivial_graph(nx.Graph())
i, cs = apxa.clique_removal(graph)
idens = nx.density(graph.subgraph(i))
eq_(idens, 0.0, "i-set not found by ramsey!")
# we should only have 1-cliques. Just singleton nodes.
for clique in cs:
cdens = nx.density(graph.subgraph(clique))
eq_(cdens, 0.0, "clique not found by clique_removal!")
graph = nx.barbell_graph(10, 5, nx.Graph())
i, cs = apxa.clique_removal(graph)
idens = nx.density(graph.subgraph(i))
eq_(idens, 0.0, "i-set not found by ramsey!")
for clique in cs:
cdens = nx.density(graph.subgraph(clique))
eq_(cdens, 1.0, "clique not found by clique_removal!")
示例7: test_ramsey
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def test_ramsey():
# this should only find the complete graph
graph = nx.complete_graph(10)
c, i = apxa.ramsey_R2(graph)
cdens = nx.density(graph.subgraph(c))
eq_(cdens, 1.0, "clique not found by ramsey!")
idens = nx.density(graph.subgraph(i))
eq_(idens, 0.0, "i-set not found by ramsey!")
# this trival graph has no cliques. should just find i-sets
graph = nx.trivial_graph(nx.Graph())
c, i = apxa.ramsey_R2(graph)
cdens = nx.density(graph.subgraph(c))
eq_(cdens, 0.0, "clique not found by ramsey!")
idens = nx.density(graph.subgraph(i))
eq_(idens, 0.0, "i-set not found by ramsey!")
graph = nx.barbell_graph(10, 5, nx.Graph())
c, i = apxa.ramsey_R2(graph)
cdens = nx.density(graph.subgraph(c))
eq_(cdens, 1.0, "clique not found by ramsey!")
idens = nx.density(graph.subgraph(i))
eq_(idens, 0.0, "i-set not found by ramsey!")
示例8: set_parser
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def set_parser(main_subparsers):
parser = main_subparsers.add_parser("generate", help="Generate Random problems")
parser.set_defaults(func=run_cmd)
parser.add_argument(
"-c",
"--correct_density",
action="store_true",
default=False,
help='In case you use the pattern "/density=d/" ('
"where d "
"is a float) in the path of the output file, "
"this argument helps you to correct the density "
"if the generated graph has a different density."
"However this rounds density to 1 decimal.",
)
# parser.add_argument('-o', '--output', nargs=1, default=None,
# help='Determines if the output is printed in console '
# 'or returned in the code. If not used, '
# 'the result is printed, else it is stored in the'
# 'file given as argument.')
subparsers = parser.add_subparsers(
title="Problems",
dest="problem",
description="The type of problem you " "want to generate",
)
# parser.set_defaults(func=run_cmd)
graphcoloring.init_cli_parser(subparsers)
meetingscheduling.init_cli_parser(subparsers)
ising.init_cli_parser(subparsers)
agents.init_cli_parser(subparsers)
scenario.init_cli_parser(subparsers)
parser_mixed_problem(subparsers)
parser_ising_soft(subparsers)
parser_iot_problem(subparsers)
parser_secp(subparsers)
示例9: correct_density
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def correct_density(filename: str, real_density: float):
path_elts = filename.split("/")
for i in range(len(path_elts)):
if path_elts[i].split("=")[0] == "density":
path_elts[i] = "density={}".format(round(real_density, 1))
return "/".join(path_elts)
示例10: test_density
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def test_density(self, process_planted):
"""Test if function returns dictionary values that are lists of tuples where the first
element is the density of the subgraph specified by the second element"""
assert all(
[
t[0] == nx.density(g_planted.subgraph(t[1]))
for l in process_planted.values()
for t in l
]
)
示例11: test_add_above_max_count_high_density
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def test_add_above_max_count_high_density(self):
"""Test if function adds subgraph tuples with density exceeding the minimum value of
``l`` even though the length of ``l`` is at its maximum"""
max_count = 10
for t in self.t_above_min_density:
l = self.l.copy()
l_ideal = sorted(l + [t], reverse=True)
subgraph._update_subgraphs_list(l, t, max_count=max_count)
del l_ideal[-1]
assert len(l) == max_count
assert l == l_ideal
示例12: test_add_above_max_count_equal_density
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def test_add_above_max_count_equal_density(self, monkeypatch):
"""Test if function randomly adds in a subgraph tuple with density equal to the minimum
value of ``l``, even though the length of ``l`` is at its maximum. This test
monkeypatches the ``np.random.choice`` call used in the function to decide whether to
keep the original subgraph or add in the new one. In one case, ``np.random.choice`` is
monkeypatched to leave ``l`` unchanged, and in another case ``np.random.choice`` is
monkeypatched to swap the minimum value of ``l`` with ``t_min_density``."""
max_count = 10
with monkeypatch.context() as m:
m.setattr(np.random, "choice", lambda x: 0)
l = self.l.copy()
subgraph._update_subgraphs_list(l, self.t_min_density, max_count=max_count)
assert len(l) == max_count
assert l == self.l
with monkeypatch.context() as m:
m.setattr(np.random, "choice", lambda x: 1)
l = self.l.copy()
subgraph._update_subgraphs_list(l, self.t_min_density, max_count=max_count)
l_ideal = self.l.copy()
del l_ideal[-1]
l_ideal.append(self.t_min_density)
assert len(l) == max_count
assert l == l_ideal
示例13: test_add_above_max_count_low_density
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def test_add_above_max_count_low_density(self):
"""Test if function does not add in a subgraph tuple of density lower than the minimum
value of ``l`` when the length of ``l`` is at its maximum"""
max_count = 10
l = self.l.copy()
subgraph._update_subgraphs_list(l, self.t_below_min_density, max_count=max_count)
assert l == self.l
示例14: _calculate_community_statistics
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def _calculate_community_statistics(self, inverse_community_index):
"""
Calculating the community level statistics used for refinement.
"""
community_statistics = {}
for comm, members in inverse_community_index.items():
induced_graph = self._graph.subgraph(members)
size = induced_graph.number_of_nodes()
density = nx.density(induced_graph)
edge_out = sum([0 if neighbor in induced_graph else 1 for node in members for neighbor in self._graph.neighbors(node)])
community_statistics[comm] = {"r":size, "d": density, "b": edge_out}
return community_statistics
示例15: internal_edge_density
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import density [as 别名]
def internal_edge_density(graph, community, **kwargs):
"""The internal density of the community set.
.. math:: f(S) = \\frac{m_S}{n_S(n_S−1)/2}
where :math:`m_S` is the number of community internal edges and :math:`n_S` is the number of community nodes.
:param graph: a networkx/igraph object
:param community: NodeClustering object
:param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
:return: If **summary==True** a FitnessResult object, otherwise a list of floats.
Example:
>>> from cdlib.algorithms import louvain
>>> from cdlib import evaluation
>>> g = nx.karate_club_graph()
>>> communities = louvain(g)
>>> mod = evaluation.internal_edge_density(g,communities)
:References:
1. Radicchi, F., Castellano, C., Cecconi, F., Loreto, V., & Parisi, D. (2004). Defining and identifying communities in networks. Proceedings of the National Academy of Sciences, 101(9), 2658-2663.
"""
return __quality_indexes(graph, community, pq.PartitionQuality.internal_edge_density, **kwargs)