You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
single_source_dijkstra algorithms with multiple target nodes (migrated from Trac #717) #703
I need to apply Dijkstra's algorithm to calculate the shortest paths from a single source node to a subset of other nodes on what will be a large graph.
Given the subset of nodes I'm interested in are generally going to be quite "close" to the source node, I don't want to have to apply Dijkstra's algorithm across the whole graph as the shortest paths to my subset of nodes will probably be found well before the entire graph has been processed.
Presently I can use single_source_dijkstra and specify a target node to stop the algorithm once a single node from my subset has been reached, but doing this for each node in my subset of target nodes is also going to be computationally wasteful, as on each occasion Dijkstra's algorithm will have to start again from scratch, and will have to repeat the same initial searches multiple times.
I'm wondering if it would be possible to extend the "target" parameter of single_source_dijkstra to accept not just a single node, but also a list of nodes?
It would also be very useful to have such an option with single_source_dijkstra_path and single_source_dijkstra_path_length as I will have occasions when I only need the paths or the path lengths.
I've been thinking about this a bit, and looking more at the code to see how things work, and I think it should be quite straightforward to modify to include a list of target nodes as a stopping rule. I've modified the code to do this and have attached the script. It certainly works, but whether its an elegant approach or not I'm not too sure - but at the least it will illustrate my point.
Now we might have trouble with nodes that are iterable (like strings) because users could set target='abc' to mean a single node or a collection of three nodes 'a', 'b', 'c'.
I think the capability you request is reasonable, but what should be the best argument system?
We could have two functions (code bloat).
We could have one function argument that tries to figure out if 'abc' is a node or not.
'''
if target_list in G:
target_list=[target_list]
'''
We could use two function arguments, one for a single target and one for multiple targets and make sure that both are not used at the same time.
'''
single_source_dijkstra(G, source, target=None, cutoff=None, weight='weight', target_list=None)
if target is not None:
if and target_list is not None:
raise ValueError("Both a single target and a target_list cannot be specified.")
else:
target_list=[target]
elif target_list is None:
target_list=[]
'''
I would have thought the simplest solution would be to adapt the code so it works with a list of nodes (along the lines I've suggested), and simply have an initial check on the target input parameter such that if the input is not a list (where someone is interested in a single target node) that single target node is turned into a list of one. So something like:
'''
if type(target) != type(list())
target = [target]
'''
This way the code could still accept a single target node, so will be compatible with the way people have been using the function, but would also allow for multiple targets as well.
That is one approach... But it requires people to create a list, and many times the nodes are not in a list. We have tried to by type neutral and let any container work in places where it can. For example, if you have a graph G and a subgraph SG and you want any nodes from the subgraph to be the target nodes, it feels more pythonic to use '''target=SG''' rather than '''target=list(SG)'''.
I agree with you that having just the one function argument is probably the best way to go. I would prefer option 2) in comment 2 to checking the type. I'll go ahead and make the change. If others want to weigh in on function arguments please do so.
I thought the request was to stop the search only after all of the targets were reached.
I'm generally not in favor of adding more complicated interfaces- I wonder if we can make a single_source_dijkstra generator of some kind that we can build all of the other functions from?
Looking again, I think you are right that the request is for a routine that stops when it has found ALL of the target nodes.
Just that ambiguity itself makes me think we shouldn't implement this feature.
You've talked about a generator for shortest_path searches before. Do you have ideas for how it would work? I could think about it, but maybe better to start with what you've come up with... At first thought, it seems like there are a lot of possibilities: yield a new unseen node, yield a node when its neighbors are looked up, yield an edge when it is crossed (again 1st time, or when taken off the queue). Perhaps best would yield a tuple in all of these cases with a flag that says what event is being yielded. Performance is of course an issue...
I backed out the change in [2180/networkx]. I don't think we should make the interface more complicated - but I don't have a proposal yet to try to simplify the shortest path code so I'll defer this ticket.
No -- finding all targets in a list can/should be done manually by the user.
At worst you can find them al one taregt at a time. Or you could use single_source_djikstra to find all nodes from one node and then eliminate the targets found doing that, wash and repeat until list of targets is small enough and then do them one at a time. You can see why its a tricky interface -- lots of different ways to do it depending on the particular situation.
I see the motivation behind why this design is tricky (it seems like the most general candidate is to pass in a lambda for filtering target nodes, which is how petgraph does it with astar), though a "multi target" dijkstra function really helps when doing a dijkstra call on a large graph but only on a few select, close-together nodes.
Another way to do a multi-target is to add a sentinel node and multiple
cost-0 edges connecting from each of your targets to the sentinel node.
Then you call Dijkstra with one target and drop the last hop.
Ale
El mié, 23 jul 2025 a las 11:02, Tristan F.-R. ***@***.***>)
escribió:
But yeah, the current interface could be extended to follow petgraph's
pattern. Target could be either None, str, Callable, if Callable, it will
return true once method returns True for that node.
El mié, 23 jul 2025 a las 12:02, Alejandro Candioti ***@***.***>)
escribió:
Another way to do a multi-target is to add a sentinel node and multiple
cost-0 edges connecting from each of your targets to the sentinel node.
Then you call Dijkstra with one target and drop the last hop.
Thanks @amcandio , this is really slick! I'd advocate for documenting it!
Activity
networkx-trac commentedon Jul 20, 2012
Attachment in Trac by t.r.etherington, 2012-04-20: single_source_dijkstra_multitarget.py
networkx-trac commentedon Jul 20, 2012
Comment in Trac by t.r.etherington, 2012-04-20
I've been thinking about this a bit, and looking more at the code to see how things work, and I think it should be quite straightforward to modify to include a list of target nodes as a stopping rule. I've modified the code to do this and have attached the script. It certainly works, but whether its an elegant approach or not I'm not too sure - but at the least it will illustrate my point.
networkx-trac commentedon Jul 20, 2012
Comment in Trac by @dschult, 2012-04-20
Now we might have trouble with nodes that are iterable (like strings) because users could set target='abc' to mean a single node or a collection of three nodes 'a', 'b', 'c'.
I think the capability you request is reasonable, but what should be the best argument system?
We could have two functions (code bloat).
We could have one function argument that tries to figure out if 'abc' is a node or not.
'''
if target_list in G:
target_list=[target_list]
'''
We could use two function arguments, one for a single target and one for multiple targets and make sure that both are not used at the same time.
'''
single_source_dijkstra(G, source, target=None, cutoff=None, weight='weight', target_list=None)
if target is not None:
if and target_list is not None:
raise ValueError("Both a single target and a target_list cannot be specified.")
else:
target_list=[target]
elif target_list is None:
target_list=[]
'''
Thoughts anyone?
networkx-trac commentedon Jul 20, 2012
Comment in Trac by t.r.etherington, 2012-04-23
I would have thought the simplest solution would be to adapt the code so it works with a list of nodes (along the lines I've suggested), and simply have an initial check on the target input parameter such that if the input is not a list (where someone is interested in a single target node) that single target node is turned into a list of one. So something like:
'''
if type(target) != type(list())
target = [target]
'''
This way the code could still accept a single target node, so will be compatible with the way people have been using the function, but would also allow for multiple targets as well.
networkx-trac commentedon Jul 20, 2012
Comment in Trac by @dschult, 2012-04-23
That is one approach... But it requires people to create a list, and many times the nodes are not in a list. We have tried to by type neutral and let any container work in places where it can. For example, if you have a graph G and a subgraph SG and you want any nodes from the subgraph to be the target nodes, it feels more pythonic to use '''target=SG''' rather than '''target=list(SG)'''.
I agree with you that having just the one function argument is probably the best way to go. I would prefer option 2) in comment 2 to checking the type. I'll go ahead and make the change. If others want to weigh in on function arguments please do so.
networkx-trac commentedon Jul 20, 2012
Comment in Trac by Dan Schult <dschult, 2012-04-25
In [cf48e75/networkx]:
'''
#!CommitTicketReference repository="networkx" revision="cf48e7537346ebf5170e04eec493fe3bd68937bb"
Allow multiple targets in single_source_dijkstra, dijkstra_path and dijkstra_path_length.
Addresses #717
'''
networkx-trac commentedon Jul 20, 2012
Comment in Trac by @hagberg, 2012-04-27
I thought the request was to stop the search only after all of the targets were reached.
I'm generally not in favor of adding more complicated interfaces- I wonder if we can make a single_source_dijkstra generator of some kind that we can build all of the other functions from?
networkx-trac commentedon Jul 20, 2012
Comment in Trac by @dschult, 2012-04-27
Looking again, I think you are right that the request is for a routine that stops when it has found ALL of the target nodes.
Just that ambiguity itself makes me think we shouldn't implement this feature.
You've talked about a generator for shortest_path searches before. Do you have ideas for how it would work? I could think about it, but maybe better to start with what you've come up with... At first thought, it seems like there are a lot of possibilities: yield a new unseen node, yield a node when its neighbors are looked up, yield an edge when it is crossed (again 1st time, or when taken off the queue). Perhaps best would yield a tuple in all of these cases with a flag that says what event is being yielded. Performance is of course an issue...
networkx-trac commentedon Jul 20, 2012
Comment in Trac by @hagberg, 2012-05-06
I backed out the change in [2180/networkx]. I don't think we should make the interface more complicated - but I don't have a proposal yet to try to simplify the shortest path code so I'll defer this ticket.
tristan-f-r commentedon Jul 21, 2025
Was there ever an implemented design for this?
dschult commentedon Jul 23, 2025
No -- finding all targets in a list can/should be done manually by the user.
At worst you can find them al one taregt at a time. Or you could use single_source_djikstra to find all nodes from one node and then eliminate the targets found doing that, wash and repeat until list of targets is small enough and then do them one at a time. You can see why its a tricky interface -- lots of different ways to do it depending on the particular situation.
tristan-f-r commentedon Jul 23, 2025
I see the motivation behind why this design is tricky (it seems like the most general candidate is to pass in a lambda for filtering target nodes, which is how petgraph does it with
astar), though a "multi target" dijkstra function really helps when doing a dijkstra call on a large graph but only on a few select, close-together nodes.amcandio commentedon Jul 23, 2025
amcandio commentedon Jul 23, 2025
rossbar commentedon Jul 24, 2025
Thanks @amcandio , this is really slick! I'd advocate for documenting it!
amcandio commentedon Jul 30, 2025
@tristan-f-r I added documentation on the sentinel approach, see https://networkx.org/documentation/latest/reference/algorithms/shortest_paths.html#notes-on-multi-target-shortest-path-queries