Repository navigation
Add Functions for Finding Connected Dominating Sets - #7774
Conversation
* Add the following functions to networkx/algorithms/dominating.py:
- connected_dominating_set for finding a connected dominating set
in undirected graphs
- interval_graph_min_connected_dominating_set for finding a minimal
connected dominating set in interval graphs
- is_connected_dominating_set to check if a set of nodes is a
connected dominating set of a graph
* Add tests for the above functions in
networkx/algorithms/tests/test_dominating.py
|
Hi, Thanks. |
|
I have added the enhancement label -- The labels are assigned by the reviewer rather than the submitter. Thanks for this! The choice of modules to add look good. I haven't looked at the content yet -- just wanted to get the label in place so you get the "green checkmarks"! :) |
|
Thanks, |
amcandio
left a comment
There was a problem hiding this comment.
Sorry for the late review. This is great functionality, left comments!
| if nx.is_dominating_set(G, nbunch) == False: | ||
| return False | ||
| SG = nx.subgraph(G, nbunch) | ||
| return nx.is_connected(SG) |
There was a problem hiding this comment.
This can be rewritten as:
return nx.is_dominating_set(G, nbunch) and nx.is_connected(nx.subgraph(G, nbunch))Which makes me think, do we really need this method?
There was a problem hiding this comment.
I agree that this function seems a bit redundant, but when developing other connected dominating set algorithms it was required quite often, and having a single function call with a declarative name was quite helpful so we included it as well. We can do without it but it makes assertions more concise.
* Add detailed algorithm description and fix runtime complexity in connected_dominating_set * Add use of itertools.count to avoid comparisons between nodes * Rewrite is_dominating_set in a more concise manner * Remove function for finding a minimal connected dominating set in interval graphs and its corresponding tests
* Add detailed algorithm description and fix runtime complexity in connected_dominating_set * Add use of itertools.count to avoid comparisons between nodes * Rewrite is_connected_dominating_set in a more concise manner * Remove function for finding a minimal connected dominating set in interval graphs and its corresponding tests
|
Minor fix of commit message: the third bullet should be "Rewrite is_connected_dominating_set..." |
amcandio
left a comment
There was a problem hiding this comment.
Good stuff. Added minor comments!
- Change docstrings to follow an imperative mood and correct a typo - Change connected_dominating_set docstring output set name - Add failure logic when input graph is disconnected - Add test to test example in docstring
amcandio
left a comment
There was a problem hiding this comment.
Amazing! Implementation looks good to me, no further comments there. I added other minor comments I missed for the unit tests.
I think we should also polish PR description a bit. Like having different sections:
- What you are adding
- Why you are adding it
- Implementation details. You can also include a brief explanation of the algorithm and quote the paper.
- How you tested it
You can use this one as an example #7945
Should I edit the original description? |
Yeah, exactly |
…st, including seed for reproduciblity
|
Please also see the updated PR description. |
dschult
left a comment
There was a problem hiding this comment.
It looks to me like this finds a spanning tree by repeatedly adding the max-remaining-degree node from all nodes connected to the existing tree.
I would have named white/gray/black as unseen, seen, dominating or something similar which provides a description of what they represent. But I'll leave that up to you.
It often amazes me how heaps end up being so efficient. :) Here, we have outdated information on the heap -- and we still update it in a lazy way that is efficient in terms of number of updates performed and always correct. On first read, it seems like a lot of updates could be needed, but further thought indicates that this is indeed a really good way to do it. :)
Thanks for this!
- Change names of data structures from white_nodes, gray_nodes, black_nodes to unseen, seen, connected_dominating_set, respectively - Update paragraph in notes to reflect the new names from above - Replace set comprehension with built-in feature for initializing degree dict - Use original heappush and heappop instead of aliases push and pop - Inline `_update` subroutine
|
Thanks for the comments and suggestions Dan.
I have updated the PR accordingly.
Gal
…On Mon, Apr 14, 2025 at 6:14 AM Dan Schult ***@***.***> wrote:
***@***.**** commented on this pull request.
It looks to me like this finds a spanning tree by repeatedly adding the
max-remaining-degree node from all nodes connected to the existing tree.
I would have named white/gray/black as unseen, seen, dominating or
something similar which provides a description of what they represent. But
I'll leave that up to you.
It often amazes me how heaps end up being so efficient. :) Here, we have
outdated information on the heap -- and we still update it in a lazy way
that is efficient in terms of number of updates performed and always
correct. On first read, it seems like a lot of updates could be needed, but
further thought indicates that this is indeed a really good way to do it. :)
Thanks for this!
------------------------------
In networkx/algorithms/dominating.py
<#7774 (comment)>:
> + NetworkXNotImplemented
+ If G is directed.
+
+ NetworkXError
+ If G is disconnected.
+
+ Notes
+ -----
+ This function implements Algorithm 1 in its basic version as described
+ in [3]_. The idea behind the algorithm is the following: grow a tree *T*,
+ starting from the vertex of maximum degree. At each step we pick a vertex
+ *v* in *T* with maximal number of white neighbors and "scan it." Scanning
+ a vertex add edges to *T* from *v* to all its neighbors not in *T*. In the
+ end we find a spanning tree *T*, and pick the nonleaf nodes as the connected
+ dominating set. Initially all vertices colored white. When we scan a vertex
+ (color it black), we mark all its neighbors that are not in *T* and and add
"and and" Also, can you switch the term "vertex" for "node" throughout
(and plurals too) to align with networkx preferred term.
If you end up changing names from white/gray/black to
unseen/seen/dominating or something else, this paragraph should be updated.
I you don't change names, you should describe what you mean by "white
nodes" before you use that term. This paragraph should probably be
rearranged anyway because the short summary uses terms not defined until
later. The part starting with "initially" might be better placed closer to
the top. But I haven't gone through it carefully. I'll just ask that you
make sure to define terms before (or as) you use them.
------------------------------
In networkx/algorithms/dominating.py
<#7774 (comment)>:
> + if len(G) == 0:
+ return set()
+
+ if not nx.is_connected(G):
+ raise nx.NetworkXError("G must be a connected graph")
+
+ if len(G) == 1:
+ return set(G)
+
+ G_succ = G._adj # For speed-up
+
+ push = heappush
+ pop = heappop
+
+ # Keep track of the number of white nodes adjacent to each vertex
+ white_degree = {v: G.degree[v] for v in G}
G.degree yields (node, degree) 2-tuples and is faster than repeatedly
calling G.degree(v).
⬇️ Suggested change
- white_degree = {v: G.degree[v] for v in G}
+ white_degree = dict(G.degree)
------------------------------
In networkx/algorithms/dominating.py
<#7774 (comment)>:
> + push = heappush
+ pop = heappop
Can we just use heappop, heappush below to reduce the indirection?
(enhance readability)
------------------------------
In networkx/algorithms/dominating.py
<#7774 (comment)>:
> + gray_nodes = []
+
+ # This will be the CDS
+ black_nodes = set()
+
+ # Use the count c to avoid comparing nodes (may not be able to)
+ c = count()
+
+ def _update(node):
+ white_nodes.remove(node)
+ push(gray_nodes, (-white_degree[node], next(c), node))
+ for nbr in G_succ[node]:
+ white_degree[nbr] -= 1
+
+ # Find node with highest degree
+ max_deg_node = max(G, key=G.degree)
You have already computed the degrees, let's use them.
⬇️ Suggested change
- max_deg_node = max(G, key=G.degree)
+ max_deg_node = max(G, key=white_degree.__getitem__)
------------------------------
In networkx/algorithms/dominating.py
<#7774 (comment)>:
> + pop = heappop
+
+ # Keep track of the number of white nodes adjacent to each vertex
+ white_degree = {v: G.degree[v] for v in G}
+
+ # Initially all nodes are white
+ white_nodes = set(G)
+
+ # We want a max-heap of the white-degree using heapq, which is a min-heap
+ # So we store the negative of the white-degree
+ gray_nodes = []
+
+ # This will be the CDS
+ black_nodes = set()
+
+ # Use the count c to avoid comparing nodes (may not be able to)
In what case might we have to compare nodes? I mean doesn't this always
avoid comparing nodes?
------------------------------
In networkx/algorithms/dominating.py
<#7774 (comment)>:
> + white_degree[nbr] -= 1
+
+ # Find node with highest degree
+ max_deg_node = max(G, key=G.degree)
+ _update(max_deg_node)
+
+ while white_nodes:
+ (neg_deg, _, u) = pop(gray_nodes)
+ # Check if u's white-degree changed while in the heap
+ if -neg_deg > white_degree[u]:
+ push(gray_nodes, (-white_degree[u], next(c), u))
+ continue
+ # Color all u's white neighbors gray
+ for v in G_succ[u]:
+ if v in white_nodes:
+ _update(v)
Can we inline the _update function here (for readability -- and to avoid
a function call which can be slow)?
I think the initialization of gray_nodes, white_nodes, could be done after
max_deg_node is known, and white_degree updated. That would avoid the
first call to _update.
—
Reply to this email directly, view it on GitHub
<#7774 (review)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AX5ZAMJE3C7IQC2KZZ6LAZL2ZMR2HAVCNFSM6AAAAABT6XF6HCVHI2DSMVQWIX3LMV43YUDVNRWFEZLROVSXG5CSMV3GSZLXHMZDONRSHE3TSNBYGY>
.
You are receiving this because you authored the thread.Message ID:
***@***.***>
|
|
I’ve removed the change to imperative mood and the comment in the parentheses. Please let me know if there’s anything else that needs changing. Thanks. |
dschult
left a comment
There was a problem hiding this comment.
I'm still working on the notes section... Can you see what you think of this suggestion?
dschult
left a comment
There was a problem hiding this comment.
One more very small change since we are in here with this code anyway.
Can you remove line 8 and line 10 (importing features from nx directly)
and replace where they are being used with nx.utils.arbitrary_element or nx.utils.not_implemented_for? That will help later when we clean up imports.
I can do that too if you prefer.
This all looks good to me!
Done! |
dschult
left a comment
There was a problem hiding this comment.
This looks good. Just a few more suggestions.
And looking forward beyond this PR. Would it be helpful to have a function that yields all the connected dominating sets? We do have a SpanningTreeIterator that yields spanning trees in order of size, so we could remove the leaves from those to get CDSs. I don't know if it would be of interest -- or even if minimum CDS is a thing people care about. But it might not be hard to use existing NX tools to build it.
- Add a "Returns" section to is_dominating_set and is_connected_dominating_set docstring - Move "Raises" section from after "Examples" section to before it - Remove imperative mood from docstring of is_dominating_set - Add clarification regarding uniqueness to is_connected_dominating_set
That's a great question. If the
Since finding a minimum CDS (MCDS) is NP-hard, this is an active research topic, especially for node/edge weighted graphs. Though here are algorithms to find an MCDS on certain types of graphs (permutation and interval graphs, and probably others). |
|
It would be great to deeply understand the relationship between spanning trees and CDS. We could even leverage the random spanning tree functionality to derive a random minimal CDS. What's not clear to me is how to guarantee that the dominating sets are drafted uniformly. |
dschult
left a comment
There was a problem hiding this comment.
I can see why this could become exponential quickly if we start removing each leaf from a tree one at a time. And then all the pairs of leaves, etc. But to find a minimum CDS we would want to remove all the leaves. Do we get close to the minimum CDS by looking at all MSTs and removing all the leaves from them?
Note that the "minimum" for CDS is just the smallest number of nodes, while the "minimum" for MST is the smallest sum of the weighted edges in the tree. So there might not be any relation at all.
Most desirable: are we guaranteed to get a MCDS by removing all leaves from all MSTs? (I suspect not, especially if they are weighted MSTs)
Pretty good: are we likely in most cases to get close to a MCDS using this approach? How close? How do you even measure how close a CDS is from a MCDS?
Probably this PR is better than that approach -- this PR uses degree info to select the nodes in the tree. So that is at least working toward fewer nodes being non-leaf. :) Thanks for this discussion.
I believe this is ready to be merged.
Correct, that's why I said just "spanning tree". Each ST could induce a minimal (not minimum) CDS once you remove the leaves and some other nodes maybe?
Regarding "pretty good" there's this paper https://arxiv.org/abs/2303.03125#:~:text=For%20an%20m%2Dedge%20connected,dear%20friend%2C%20Professor%20Takao%20Nishizeki. If I understand that correctly, the algorithm finds a spanning tree with at most 2x more leaves than optimal solution. Meaning that you can probably use that algo to induce a CDSs of size S where |G|-|S| is at most 2x from optimum.
+1 Good job @GalMichaeli! |
Added Functionality
This PR extends the functionality of
networkx/networx/algorithms/dominating.pyby adding two functions:connected_dominating_set- takes an undirected connected graphGand returns a connected dominating set (CDS) of G
is_connected_dominating_set- takes an undirected graphGand an iterable
nbunchand returns true if and only ifnbunchis a CDS of
GMotivation
NetworkX is used extensively in the Networked Software Systems Lab at
the Technion - Israel Institute of Technology during reseach of various
networking topics. Finding a connected dominating set (CDS) in the
context of networks, especially in wireless or ad hoc networks, is
crucial for optimizing communication and resource usage. A CDS serves as
a virtual backbone for the network, meaning efficient routing, power
conservation and network coverage.
Implementation Details
The function
connected_dominating_setis an implementation ofAlgorithm I as described in this paper. Quoting from the paper,
"The idea behind the algorithm is the following: grow a tree T,
starting from the vertex of maximum degree. At each step we pick
a vertex v in T and 'scan it.' Scanning a vertex adds edges to T from v
to all its neighbors not in T. In the end we find a spanning tree T,
and pick the nonleaf nodes as the connected dominating set."
Testing Details
In order to test
is_connected_dominating_setwe create a path graph Gwith four nodes: 0 <-> 1 <-> 2 <-> 3. We then assert that {1, 2} is a
CDS, {1, 3} is NOT a CDS and that {2, 3} indeed induces a connected
subgraph of G but is not a dominating set.
As for
connected_dominating_set, we first test for the expected behaviorin edge cases, i.e., when G is the null graph, G has only one node and G
is disconnected. Next we test that for complete graphs the function
returns a CDS of size 1. Finally, we define a parametrized test, in which
we test connected Watts-Strogatz graphs with varying parameters and
parametrized seed for reproducibility.