In networkx,
shortest_path(G, source=None, target=None, weight=None)
# weight/distance/cost 1 by default
can support edge proprety “weight” as operator to calculate the shortest path between two node in graph.
However, if i have other meta class attached with a node/edge, for example:
class meta( object ):
def __init__( self, weight_shift = 1 ):
self.weight_shift = weight_shift
G.add_node('A', meta_data = meta( weight_shift = 100 ) )
G.add_node('B', meta_data = meta( weight_shift = 200 ) )
G.add_node('C')
...
G.add_edge("A", "C", weight=10, meta_data = meta( weight_shift = -5 ))
G.add_edge("B", "C", weight=10, meta_data = meta( weight_shift = -10 ))
G.add_edge("A","B")
is it possible to define a function as weight parameter for shortest_path()?
def weight_sum():
...
Which can calculate the “weight” in “runtime”, for example, use logic:
weight_sum = edge.weight + edge.meta.weight_shift + node_left.meta.weight_shift + node_right.meta.weight_shift
then
shortest_path(G, source="A", target="B", weight=weight_sum())
to get the shortest path?
THANKS.
It’s not possible with the current implementation in NetworkX.
Two options are:
1) Before your shortest path search process all of the edges to add a new edge attribute according to your weight function. Use that attribute as the ‘weight’ argument to shortest_path()
2) Replace the lines like
in the code for Dijkstra’s algorithm to use your custom function for the edge weight instead of getting the ‘weight’ attribute.